C++ algorithm search() function
Example
Find out if a vector is contained in another vector:
vector<int> numbers = {1, 7, 3, 5, 9, 2};
vector<int> target = {3, 5, 9};
if (search(numbers.begin(), numbers.end(), target.begin(), target.end()) != numbers.end()) {
cout << "Target was found";
} else {
cout << "The target was not found";
}
Try it Yourself »
Definition and Usage
The search()
function searches a data range for a sequence of values specified by another data range and returns an iterator pointing to the position at which it is found.
The data ranges are specified by iterators.
Syntax
search(iterator start, iterator end, iterator search_start, iterator search_end);
Parameter Values
Parameter | Description |
---|---|
start | Required. An iterator pointing to the start of the data range to search in. |
end | Required. An iterator pointing to the end of the data range to search in. Elements up to this position will be included, but the element at this position will not be. |
search_start | Required. An iterator pointing to the start of a data range containing the sequence to search for. |
search_end | Required. An iterator pointing to the end of a data range containing the sequence to search for. Elements up to this position will be included, but the element at this position will not be. |
Technical Details
Returns: | An iterator pointing to the position in the first data range where the sequence starts. If the sequence was not found then the end of the first data range is returned. |
---|
Related Pages
Read more about data structures in our Data Structures Tutorial.
Read more about iterators in our Iterators Tutorial.
Read more about algorithms in our Algorithms Tutorial.