C++ 在stl算法中移动迭代器
在循环中是否有前进(或后退)的方法 比如说C++ 在stl算法中移动迭代器,c++,c++11,C++,C++11,在循环中是否有前进(或后退)的方法 比如说 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 } }); 向量s{1,
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
}
});
向量s{1,2,3,4,5,6,7,8};
对于每个(开始、结束),[](){
if(..)//将迭代器向前移动2个空格的逻辑
{
下一个(s);
}
否则{
//正常处理
}
});
当然,常规for循环也做同样的事情,但如果可以的话,我想避免它
for(auto i = 0UL; i < size();) {
i+=2;
}
用于(自动i=0UL;istd::for_each
中没有可移植的方法来拦截迭代
但是,如果您真的无法忍受使用常规for
循环和std::size\u t
的(上级?)方式,您可以自己处理迭代
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
中没有可移植的方法来拦截迭代
但是,如果您真的无法忍受使用常规for
循环和std::size\u t
的(上级?)方式,您可以自己处理迭代
for (auto/*ToDo - perhaps & here*/ it = s.begin(); it != s.end(); ++it){
// You can advance `it` with `++it` and retard it with `--it`.
}
当控件到达
UnaryFunction
时,您不会使用std::for_each
与迭代器交互,因为它们已被取消引用
您可以使用lambda关闭一个“skip now”变量,并对其进行测试以尽早返回
e、 g
int skip\u count=0;
向量s{1,2,3,4,5,6,7,8};
对于每个(开始、结束、[&跳过计数](){
如果(跳过计数)
{
--跳过计数;
返回;
}
否则如果(/*某些测试*/){
跳过计数=2;
}
否则{
//正常处理
}
});
当控件到达UnaryFunction
时,您不会使用std::for_each
与迭代器交互,迭代器已被解除引用
您可以使用lambda关闭一个“skip now”变量,并对其进行测试以尽早返回
e、 g
int skip\u count=0;
向量s{1,2,3,4,5,6,7,8};
对于每个(开始、结束、[&跳过计数](){
如果(跳过计数)
{
--跳过计数;
返回;
}
否则如果(/*某些测试*/){
跳过计数=2;
}
否则{
//正常处理
}
});
如果你增加迭代器,那么它实际上不是每个的,
当你像这样操作索引时,如果你增加迭代器,那么一个普通的循环会更清晰,那么它就不是一个真正的for_each
循环了,我的意图是:在for
循环中,我有一个使用项目的递归函数(类似于lexer),所以我的目的是对输入进行std::累加,但不总是一个值。我大体上同意,在这种情况下,naïve for循环很好。我的具体用例是:在for
循环中,我有一个使用项的递归函数(类似于lexer),因此我的意图是对输入进行std::累加,但不总是一个值。我大体上同意,在这种情况下,天真的for循环是好的