The search()
function in C++ helps search for a sequence of elements inside an array/vector. This function is available in the <algorithm.h>
header file.
The search()
function accepts the following parameters:
first1, last1
: These are the iterators pointing to the initial and final positions of the array/vector where the search operation needs to be performed.
first2, last2
: These are the iterators pointing to the initial and final positions of the array/vector that needs to be searched.
pred
: This is an optional parameter that specifies a binary function that returns a boolean value, which indicates how to perform the search.
The search()
function returns an iterator that points to the first occurrence of the sequence in the range [first2, last2) in the sequence [first1, last1). If the value is not found, then it returns an iterator to last1
of the array or vector.
Let’s take a look at the code.
#include <iostream>#include <algorithm>#include <vector>using namespace std;int main () {vector<int> vec;for (int i = 1; i <= 10; i++)vec.push_back(i*10);int seq[] = {40,50,60,70};auto it = search(vec.begin(), vec.end(), seq, seq + 4);if (it!=vec.end())cout << "Sequence found at position " << (it-vec.begin());elsecout << "Sequence not found";return 0;}
search()
function and pass all the required parameters.it
points to the end of the vector.Now, let us look at code where we use a binary predicate to perform the search.
#include <iostream>#include <vector>#include <algorithm>using namespace std;bool pred (int i, int j) {return (i==j);}int main() {vector<int> vec;for (int i = 1; i <= 10; i++)vec.push_back(i*10);int seq[] = {20,30,50};auto it = search (vec.begin(), vec.end(), seq, seq + 3, pred);if (it!=vec.end())cout << "Sequence found at position " << (it-vec.begin());elsecout << "Sequence not found";return 0;}
search()
function and pass all the required parameters.it
points to the end of the vector.