原型:
#include <algorithm>
forward_iterator adjacent_find( forward_iterator start, forward_iterator end );
forward_iterator adjacent_find( forward_iterator start, forward_iterator end, BinPred pr );
函数adjacent_find()搜索start和end之间的相邻的两个相同元素. 如果二元谓词pr没有被指定, 则使用它检查两个元素是否相等. 如果被指定,则使用这个pr做operator来对start和end两个iterator指向的元素来做运算。返回值是一个迭代器, 它指向被发现的元素对的第一个元素. 如果没有匹配的元素, 则返回迭代器end.
看下面的例子:
#include <vector>
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
class TwiceOver
{
public:
bool operator () (int val1, int val2)
{
return val1 == (val2 / 2) ? true: false;
}
};
int main(int argc, char* argv[] )
{
int ia[] = { 1, 2, 4, 4, 8 };
std::vector<int> vec( ia, ia+5);
int *piter = NULL;
int *piter2 = NULL;
vector<int>::iterator iter;
piter = adjacent_find(ia, ia + 5);
assert(*piter == ia[2]);
cout << "The two equal ints' value is:" << *piter << endl;
iter = adjacent_find(vec.begin(), vec.end(), TwiceOver() );
//piter2 = adjacent_find(ia,ia+4, TwiceOver() );
//assert( *piter2 == ia[2] );
assert( *iter = vec[1] );
cout << "OK: adjacent_find() succeeded!" << endl;
cout << "The values of the first occurence of TwiceOver is: "<< *iter << ". " << endl;
system("pause");
return 0;
}