一:用法解析


函数原型:

equality (1)    
template <class ForwardIterator>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);
predicate (2)   
template <class ForwardIterator, class BinaryPredicate>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last,
                                  BinaryPredicate pred);

功能:

在区间[ first ,last )找到第一组邻近相等(或者可使pred为真)的元素,返回该组的第一个元素的迭代器,如果找不到last。

例子:

// adjacent_find example
#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;
}

运行如下:

the first pair of repeated elements are: 30
the second pair of repeated elements are: 10


二:源码剖析
// TEMPLATE FUNCTION adjacent_find WITH PRED
template<class _FwdIt,
class _Pr> inline
_FwdIt _Adjacent_find(_FwdIt _First, _FwdIt _Last, _Pr _Pred)
{ // find first satisfying _Pred with successor
if (_First != _Last)
for (_FwdIt _Firstb; (void)(_Firstb = _First), ++_First != _Last; )
if (_Pred(*_Firstb, *_First))
return (_Firstb);
return (_Last);
}

template<class _FwdIt,
class _Pr> inline
_FwdIt adjacent_find(_FwdIt _First, _FwdIt _Last, _Pr _Pred)
{ // find first satisfying _Pred with successor
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER_IF(_First != _Last && _STD next(_First) != _Last, _Pred);
return (_Rechecked(_First,
_Adjacent_find(_Unchecked(_First), _Unchecked(_Last), _Pred)));
}

// TEMPLATE FUNCTION adjacent_find
template<class _FwdIt> inline
_FwdIt adjacent_find(_FwdIt _First, _FwdIt _Last)
{ // find first matching successor
return (_STD adjacent_find(_First, _Last, equal_to<>()));
}





源码摘抄自Visual Studio 2015安装目录algorithm文件中。

点击进入目录----> ​​C++源码剖析目录​​