有没有办法在循环中向前(或向后)移动
例如
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`.
}
关于c++ - 在 STL 算法中移动迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076298/