[英]Moving an iterator while in a stl algorithm
在循环中是否有前进或后退的方法
例如
vector<int> s{1,2,3,4,5,6,7,8};
for_each(begin(s), end(s), []() {
if(....) // Some logic that moves the iterator forward 2 spaces
{
next(s);
}
else {
// Normal processing
}
});
当然,常规的for循环也做同样的事情,但是如果可以的话,我想避免这样做。
for(auto i = 0UL; i < size();) {
i+=2;
}
从某种意义上讲,没有可移植的方法来拦截std::for_each
的迭代。
但是,如果您真的不能忍受使用带有std::size_t
的常规for
循环的(高级?)方法,则可以自己处理迭代。
for (auto/*ToDo - perhaps & here*/ it = s.begin(); it != s.end(); ++it){
// You can advance `it` with `++it` and retard it with `--it`.
}
您不会通过std::for_each
与迭代器进行交互,直到控件到达您的UnaryFunction
它们才被取消引用。
您可以使用lambda关闭“立即跳过”变量,并对其进行测试以早日返回。
例如
int skip_count = 0;
vector<int> s{1,2,3,4,5,6,7,8};
for_each(begin(s), end(s), [&skip_count]() {
if(skip_count)
{
--skip_count;
return;
}
else if ( /* Some test */ ) {
skip_count = 2;
}
else {
// Normal processing
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.