C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Algorithm Functions search_n()C++ Algorithm search_n() function searches the container [first,last) for the occurrence of a sequence of count elements, that is every element is searched to check whether it satisfies a given pred. An iterator to first element satifisying the condition is returned, else an iterator to last is returned. Syntaxtemplate<class ForwardIterator,class Size,class T> ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T&val); template<class ForwardIterator, class Size, class T, class BinaryPredicate> ForwardIterator search_n ( ForwardIterator first, ForwardIterator last, Size count, const T& val, BinaryPredicate pred); Parameterfirst: It is a forward iterator to the first element of the range, where the element itself is included in the range. last: It is a forward iterator to the last element of the range, where the element itself is not included in the range. count: It gives the least number of elements that are supposed to be matching a condition. val: The argument specifies the conditional value or the pred condition for which the function search_n is applied on a range. pred: It is a Binary function that accepts two arguments, and gives a boolean result. Return valueThe function returns an iterator to the first element which matches the pred, if no such element is found then an iterator to the last element is returned. Example 1#include<iostream> #include<algorithm> #include<vector> bool newpred(int m, int n) { return(m==n); } int main() { int newints[]={40,50,60,60,50,40,40,50}; std::vector<int> newvector(newints, newints+8); std::vector<int>::iterator ti; ti=std::search_n (newvector.begin(),newvector.end(),2,60); if(ti!=newvector.end()) std::cout<<"Two times 60 has been found at position"<<(ti- newvector.begin())<<"\n"; else std::cout<<"No match of 60 has been found \n"; return 0; } Output: Two times 60 has been at position 2 Example 2#include <iostream> #include <vector> #include <algorithm> using namespace std; bool newpred(int m, int n) { return(m==n); } int main() { int m, n; vector<int> u1 = { 11, 22, 33, 44, 55, 33, 33, 66, 77 }; int u2 = 33; vector<int>::iterator ti; ti = std::search_n(u1.begin(), u1.end(), 2, u2, newpred); if (ti!= u1.end()) { cout << "Value u2 has been found at position " << (ti - u1.begin()); } else { cout << "Value u2 is not present" << "in vector u1"; } return 0; } Output: Value u2 has been found at position 5 ComplexityThe complexity of the function is linear starting from the first element to the last one. Data racesSome or all of the container objects are accesed. ExceptionsThe function throws an exception if any of the container elements throws one.
Next TopicC++ Algorithm swap Function
|