C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Algorithm Function adjacent_find()C++ Algorithm adjacent_find() function performs a search operation on the range [first, last] for the very first occurrence of two consecutive matching elements. If such elements are found then an iterator to the first element of the two is returned. Otherwise, the last element is returned. Syntaxtemplate<class ForwardIterator> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last); template<class ForwardIterator, class BinaryPredicate> ForwardIterator adjacent_find(ForwardIterator first,ForwardIterator last BinaryPredicate pred); Parameterfirst: It is a forward iterator to the first element in the range. last: It is a forward iterator to the last element in the range. 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 range[first,last) if two consecutive matching elements are found else the last element is returned. Example 1#include<iostream> #include<algorithm> #include<vector> using namespace std; bool myfunc(int j, int k) { return(j==k); } int main() { int newints[]={5,20,5,50,50,20,60,60,20}; std::vector<int> newvector(newints, newints+8); std::vector<int>::iterator ti; ti=std::adjacent_find(newvector.begin(),newvector.end()); if(ti!=newvector.end()) std::cout<<"In the given range the first pair of sequence that is repeated is:"<<*ti<<"\n"; ti=std::adjacent_find(++ti,newvector.end(),myfunc); if(ti!=newvector.end()) std::cout<<"In the given range the second pair of sequence that is repeated is:"<<*ti<<"\n"; return 0; } Output: In the given range the first pair of sequence that is repeated are: 50 In the given range the second pair of sequence that is repeated are: 60 Example 2#include<iostream> #include<algorithm> int main() { int A[]={12,14,17,17,19}; int n=sizeof(A)/sizeof(A[0]); int* ti=std::adjacent_find(A,A+n); std::cout<<*ti; } Output: 17 ComplexityThe complexity of the function is linear up to a distance between the first and last element. Data racesSome or all of the elements of the range are accessed. ExceptionsThe function throws an exception if any of the argument throws one.
Next TopicC++ Algorithm any_of Function
|