Connecting Tech Pros Worldwide Help | Site Map

Finding a vector within another vector?

Newbie
 
Join Date: Nov 2009
Posts: 2
#1: 3 Weeks Ago
So I'm doing this assignment for a class, and need to write a function that will basically find all elements of a vector in another vector in the same exact order, then return the starting position of the sequence. Here's what I've tried:

Expand|Select|Wrap|Line Numbers
  1. for (int k = 0; k != v1.size(); k++)
  2.     {
  3.         if (v2[0] == v1[k])
  4.         {
  5.             int l = k;
  6.             int j = 0;
  7.             while (v1[l] == v2[j])
  8.             {
  9.                 while (l != v1.size() && j != v2.size())
  10.                 {
  11.                     l++;
  12.                     j++;
  13.                 }
  14.                 return k;
  15.             }
  16.  
  17.         }
  18.     }
It works fine as long as there are no repeated elements. For example, if I'm looking for a vector{1, 2, 3, 4} within vector {5, 6, 7, 1, 2, 3, 4, 2, 3}, it will come out fine, but if I try it with vector{1, 2, 3, 1, 2, 3, 4}, it fails on me.
Needs Regular Fix
 
Join Date: Jul 2008
Posts: 381
#2: 3 Weeks Ago

re: Finding a vector within another vector?


It don't work at all - it return index as 'matching' element there matches first element of v2.
E.g if v2 = {1,1,2,3,4}; Hint - how many times does condition on line 7 execute?
Newbie
 
Join Date: Nov 2009
Posts: 2
#3: 2 Weeks Ago

re: Finding a vector within another vector?


Ah, actually I figured it out. Had to rewrite the two while loops and it worked fine.
Reply

Tags
c++, function, vectors


Similar C / C++ bytes