c++ - 在 STL 算法中移动迭代器

标签 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
    }
});

当然,常规的 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/

相关文章:

c++ - 如何在不知道 C++ 基类名称的情况下调用子类中基类的成员?

c++ - 从具有成员函数的共享指针的 std::vector 中移除_if

C++ - 引用参数的常量值?

C++运算符的多重定义>>

java - 在 C++ 中怎么说 != 0-9

c++ - 可以推断左值引用非类型模板参数吗?

c++ - 用另一个函数模板重载一个函数模板是否合法?

c++ - Qt5 在多宿主网络上绑定(bind) TCP 套接字

c++ - 将 braced-init-list 分配给数组是否正确?

c++ - 有什么方法可以使用 GCC 的 __thread 完全模拟 thread_local 吗?