The search_n()
function is used to search in a range for the occurrence of a sequence of elements occurring at least n times in the range.
The search_n()
function accepts the following parameters:
Begin
: This is the iterator pointing to the beginning of the position from which the values need to be searched.End
: This is the iterator pointing to the ending position to which the values need to be searched.Count
: This is the minimum number of successive elements to match.Value
: This is the value that needs to be searched.The function returns an iterator to the first element that matches the searched value. If no such element is found, then an iterator to the last element is returned.
Let’s have a look at the code.
#include <iostream>#include <algorithm>#include<vector>using namespace std;int main(){int a[]={41,6,6,6,50,47,47,47};vector<int> v(a,a+8);vector<int>::iterator ti;ti = search_n (v.begin(),v.end(),3,47);if(ti != v.end())cout<<"3 times 47 has been found at position: "<<(ti-v.begin())<<"\n";elsecout<<"No match of 47 has been found \n";return 0;}
In lines 1 to 3, we imported the required libraries.
In line 6, we made a main()
function.
In line 8, we initialized an array.
In line 9, we declared a vector of size equal to array.
In line 10, we declared an iterator to a vector.
In line 12, we used the search_n()
function to search 3 consecutive values = 47
.
In line 14, we used an if-else statement to check for the desired value and display the position with the message.
In this way, we can use the search_n()
function to search in a range for the occurrence of a sequence of elements occurring at least n times.