C++算法neighbor_find()函数在两个连续匹配元素的最先出现的参数[first,last]上执行搜索操作。如果找到这样的元素,则返回两个元素的第一个元素的迭代器。否则,返回最后一个元素。
template<class ForwardIterator> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last); template<class ForwardIterator, class BinaryPredicate> ForwardIterator adjacent_find(ForwardIterator first,ForwardIterator last BinaryPredicate pred);
第一:它是参数中第一个元素的正向迭代器。
最后:它是参数中最后一个元素的前向迭代器。
pred :它是一个二进制函数,接受两个元素作为参数并执行该函数设计的任务。
如果找到两个连续的匹配元素,则该函数将迭代器返回到range [first,last)的第一个元素,否则返回最后一个元素。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-algorithm-adjacent-find-function.html
来源:LearnFk无涯教程网
#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; }
输出:
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
#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; }
输出:
17
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)