Finding a vector within another vector?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • danime91
    New Member
    • Nov 2009
    • 2

    Finding a vector within another vector?

    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:

    Code:
    for (int k = 0; k != v1.size(); k++)
    	{
    		if (v2[0] == v1[k])
    		{
    			int l = k;
    			int j = 0;
    			while (v1[l] == v2[j])
    			{
    				while (l != v1.size() && j != v2.size())
    				{
    					l++;
    					j++;
    				}
    				return k;
    			}
    			
    		}
    	}
    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.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    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?

    Comment

    • danime91
      New Member
      • Nov 2009
      • 2

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

      Comment

      Working...