By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,156 Members | 1,026 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,156 IT Pros & Developers. It's quick & easy.

Finding a vector within another vector?

P: 2
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.
Nov 3 '09 #1
Share this Question
Share on Google+
2 Replies


100+
P: 687
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?
Nov 3 '09 #2

P: 2
Ah, actually I figured it out. Had to rewrite the two while loops and it worked fine.
Nov 3 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.