c++ - 这个std::adjacent_find的等价实现是正确的吗?
ringa_lee
ringa_lee 2017-04-17 13:33:22
0
1
391

在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 )貌似就正确了


是我理解错了还是代码错了? 求解答,可能这个问题很弱智,

ringa_lee
ringa_lee

ringa_lee

reply all(1)
PHPzhong

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/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template