![](/img/trans.png)
[英]Why std::lock() causes the endless loop when works with my own unique_lock object?
[英]std::advance() causes endless loop
我有一個使用std::advance()
的代碼片段。
使用std::advance()
時如何避免無限循環?
std::list<xxx>::iterator i = ppp.begin();
std::advance(i, yyy);
也許您的意思是,應該如何避免運行通過end()迭代器。
在這種情況下,只需檢查
std::advance(i, std::min(yyy, std::distance(i, ppp.end()));
或者,圍繞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));
}
請注意 ,最后運行的是Undefined Behavior ,這與無限循環完全不同。 它可能具有相同的“表觀”效果(當然,這就是UB的本質)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.