本文内容来自C++Plus,本文只是本人的总结和翻译而已。本人只是C++的搬运工。
原文传送门:http://www.cplusplus.com/reference/algorithm/adjacent_find/
adjacent_find()算法:查找相邻且相等的元素。
作用:查找一个区间[First,Last)之间是否有相邻且相等的元素。若果有就返回这两个元素中的第一个元素的迭代器对象并且返回,如果一直没有找到就返回last。
template <class ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last)
{
if (first != last)
{
ForwardIterator next=first; ++next;
while (next != last) {
if (*first == *next) // or: if (pred(*first,*next)), for version (2)
return first;
++first; ++next;
}
}
return last;
}
#include <iostream> // std::cout
#include <algorithm> // std::adjacent_find
#include <vector> // std::vector
bool myfunction (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {5,20,5,30,30,20,10,10,20};
std::vector<int> myvector (myints,myints+8);
std::vector<int>::iterator it;
// using default comparison:
it = std::adjacent_find (myvector.begin(), myvector.end());
if (it!=myvector.end())
std::cout << "the first pair of repeated elements are: " << *it << '\n';
//using predicate comparison:
it = std::adjacent_find (++it, myvector.end(), myfunction);
if (it!=myvector.end())
std::cout << "the second pair of repeated elements are: " << *it << '\n';
return 0;
}
注意点:
1. pred可以添加一个进行比较的条件,当调用这个bool函数的时候,就会按照里面设置好的条件查找,比如,查找两个相邻且相等都为奇数的数。
2. adjacent_find()算法如果不传递 perd 进去的话就只是一个在区间内查找相邻相等数的算法。
3.每次查找只会返回第一次找到的符合条件的两个相邻数,如果想在同一个空间内多次查找,只能拿着上次返回处的迭代器继续查找。