Solved

# Searching a vector for a vector.

Posted on 2008-06-16
185 Views
Hi,

Is there some STL method that lets me search a vector of values from a certain index for another vector of values and telling me the returned index?

Thanks,
Uni
0
Question by:Unimatrix_001
• 3

LVL 53

Accepted Solution

Infinity08 earned 500 total points
ID: 21792108
You mean you want to find the first occurrence of the entire second vector in the first ? If so, take a look at the search algorithm for example :

http://www.cplusplus.com/reference/algorithm/search.html
``````std::vector<int> vec;       // <--- the vector

std::vector<int> pattern;   // <--- the pattern we want to find

std::vector<int>::iterator it = search(vec.begin(), vec.end(), pattern.begin(), pattern.end());

if (it != vec.end()) {

// found pattern at iterator it

}
``````
0

LVL 53

Expert Comment

ID: 21792115
Or do you want to find any value from the second vector in the first ? If so, take a look at the find_first_of algorithm :

http://www.cplusplus.com/reference/algorithm/find_first_of.html

``````std::vector<int> vec;       // <--- the vector

std::vector<int> match;     // <--- the values we want to find

std::vector<int>::iterator it = find_first_of(vec.begin(), vec.end(), pattern.begin(), pattern.end());

if (it != vec.end()) {

// found a match at iterator it

}
``````
0

LVL 53

Expert Comment

ID: 21792122
Obviously in the second code sample, pattern should have been replaced by match :
``````std::vector<int> vec;       // <--- the vector

std::vector<int> match;     // <--- the values we want to find

std::vector<int>::iterator it = find_first_of(vec.begin(), vec.end(), match.begin(), match.end());

if (it != vec.end()) {

// found a match at iterator it

}
``````
0

LVL 3

Author Closing Comment

ID: 31467532
That's the one. :)
0

## Featured Post

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.