在ClassFoo网站看到std::adjacent_find的等价实现,感觉代码有一点点错误,不知道是不是我的错觉
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);
}
其中for (_FwdIt _Firstb; (_Firstb = _First), ++_First != _Last; )
循环的终止条件为++_First
不等于_Last
,先自增后比较,这样貌似提前一个元素结束了循环
改成for(_FwdIt _Firstb = _First ; _Firstb != _Last ; ++ _Firstb )
貌似就正确了
是我理解错了还是代码错了? 求解答,可能这个问题很弱智,
PHPz2017-04-17 13:35:22
There is a problem with your understanding.
If++_First != _Last
is not true, it means that there is only one element left, but the goal of adjacent_find
is to find a pair of adjacent elements in [_First, _Last)
that meet the conditions specified by _Pred
. There is only one element left which cannot make a pair anyway.
You can check out the API description on the cpp official website:
http://www.cplusplus.com/reference/algorithm/adjacent_find/