adjacen_find:搜索给定区间中两个连续相等的元素
这个函数也以重载的形式给出了这两个函数.一个是默认的关系运算(==),一个是仿函数
//TEMPLATE FUNCTION adjacent_find
template<class_FwdIt>inline
_FwdIt _Adjacent_find(_FwdIt _First,_FwdIt _Last)
{ // find first matching successor
if(_First != _Last)
for(_FwdIt _Firstb; (_Firstb = _First), ++_First != _Last; )//首先保存起始元素.然后和下一个 //元素进行比较.如果相等则返回之前保
//存的那个元素,否则进行下次比较.
//需要注意的是,这里用了一些技巧,首先是使用了逗号表达式,其次是使用++_First == _Last.
if (*_Firstb == *_First)
return (_Firstb);
return(_Last);
}
template<class_FwdIt>inline
_FwdIt adjacent_find(_FwdIt _First,_FwdIt _Last)
{ // find first matching successor
_DEBUG_RANGE(_First, _Last);
return(_Rechecked(_First,
_Adjacent_find(_Unchecked(_First),_Unchecked(_Last))));
}
adjacen_find:搜索给定区间中连续使得_Pred为真的元素位置.
//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; (_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(_Pred);
return(_Rechecked(_First,
_Adjacent_find(_Unchecked(_First),_Unchecked(_Last), _Pred)));
}
照样还是举例说明吧!
举例:
template<typenameT>
bool equal_three( T _value1,T _value2 )
{
return_value1 == ++ _value2;
}
int main()
{
vector<int>vecInt;
vecInt.push_back( 5 );
vecInt.push_back( 2 );
vecInt.push_back( 3 );
vecInt.push_back( 2 );
vecInt.push_back( 9 );
vecInt.push_back( 9 );
vecInt.push_back( 5 );
vecInt.push_back( 4 );
vecInt.push_back( 3 );
vector<int>::iteratoriterFind = adjacent_find( vecInt.begin(),vecInt.end() );
if (iterFind != vecInt.end() )
{
cout<<*(--iterFind)<<"\n";
}
iterFind = adjacent_find(vecInt.begin(),vecInt.end(),equal_three<int>);
if (iterFind != vecInt.end() )
{
cout<<distance(vecInt.begin(),iterFind ) + 1<<"\n";
}
system( "pause");
return0;
}
程序输出:
2
3
需要注意的是前一个2是vecInt的第3个元素.仿函数那个例子需要注意是*_First== ++ *_First来比较