简体   繁体   English

std :: advance()导致无限循环

[英]std::advance() causes endless loop

I have a code fragment that uses std::advance() . 我有一个使用std::advance()的代码片段。

How to avoid endless loop when using std::advance() ? 使用std::advance()时如何避免无限循环?

std::list<xxx>::iterator i = ppp.begin();
std::advance(i, yyy);

Maybe you mean, how should you avoid running past the end() iterator. 也许您的意思是,应该如何避免运行通过end()迭代器。

In that case, just either check 在这种情况下,只需检查

std::advance(i, std::min(yyy, std::distance(i, ppp.end()));

Or, write a wrapper around std::advance/std::next that checks for end iterators more efficienttly: http://ideone.com/7DYSSn 或者,围绕std :: advance / std :: next编写包装器,以更高效地检查最终迭代器: http : //ideone.com/7DYSSn

#include <list>
#include <cassert>

template <typename It>
   It safe_next(It it, std::size_t steps, It end)
{
    while (it!=end && steps--)
        it++;

    return it;
}

int main()
{
    std::list<int> l { 1,2,3,4,5,6,7,8 };
    auto it = begin(l);

    assert(safe_next(it, 3, end(l)) == std::next(it, 3));
    assert(safe_next(it, 30, end(l)) == end(l));

    // the `distance` trick also works:
    assert(next(it, std::min(30l, std::distance(it, end(l)))) == end(l));
}

Note that running past the end is Undefined Behaviour , which is a completely different thing than an infinite loop. 请注意 ,最后运行的是Undefined Behavior ,这与无限循环完全不同。 It might have the same "apparent" effect (but that's the nature of UB, of course). 它可能具有相同的“表观”效果(当然,这就是UB的本质)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM