C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Algorithm Function search()C++ Algorithm search() function searches the range [first1, last1) for the occurrence of a subsequence defined by the range [first2, last2), and an iterator to the first element is returned. If the subsequence does not exist then an iterator to the last1 is returned. Syntaxtemplate<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator last1, ForwardIterator2 first2, ForwardIterator2 last2); template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); Parameterfirst1: It is a forward iterator to the first element of the [first1, last1). last1: It is a forward iterator to the last element of the [first1, last1). first2: It is a forward iterator to the first element of the [first2, last2). pred: It is a binary function that accepts two elements as arguments and performs the task designed by the function. Return valueThe function returns an iterator to the first element of the first occurrence of the subsequence, else returns the last1 element. Example 1#include <iostream> #include <algorithm> #include <vector> bool newpredicate (int m, int n) { return (m==n); } int main () { std::vector<int> haystack; for (int a=1; a<10; a++) haystack.push_back(a*10); int patt1[] = {20,30,40,50}; std::vector<int>::iterator ti; ti = std::search (haystack.begin(), haystack.end(), patt1, patt1+4); if (ti!=haystack.end()) std::cout << "patt1 found at position " << (ti-haystack.begin()) << '\n'; else std::cout << "patt1 not found\n"; int patt2[] = {40,35,50}; ti = std::search (haystack.begin(), haystack.end(), patt2, patt2+3, newpredicate); if (ti!=haystack.end()) std::cout << "patt2 found at position " << (ti-haystack.begin()) << '\n'; else std::cout << "patt2 not found\n"; return 0; } Output: patt1 found at position 1 patt2 not found Example 2#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int m, n; vector <int> u1={1,2,3,4,5,6,7}; vector <int> u2={3,4,5}; vector<int>::iterator ti; ti = std::search(u1.begin(), u1.end(), u2.begin(),u2.end()); if(ti!=u1.end()) { cout<<"Vector2 is present at index:"<<(ti-u1.begin()); } else { cout<<"In vector1, vector2 is not present"; } return 0; } Output: Vector2 is present at index:2 ComplexityThe function has linear complexity from the first1 element to the last1 element. Data racesObjects in both ranges are accessed. ExceptionsThe function throws an exception if any of the argument throws one.
Next TopicC++ Algorithm is_permutation Function
|