c ++通过具有可变方向的向量迭代

orm*_*rin 1 c++ stl

我想知道是否有任何想法如何在输入迭代方向时迭代向量(或容器)的元素.

这是我能想到的第一件事:

    std::vector<int> vec = {1, 2, 3, 4};
    int direction = 1 // or -1;
    int start = direction == 1 ?  0 : (int)arrs.size()-1;
    for (int i=start; i<(int)vec.size() && 0<=i; i+=direction) {
      // do your stuff
    }
Run Code Online (Sandbox Code Playgroud)

有谁知道更好或更好的方法来做到这一点?

jua*_*nza 6

我会这样,使用标准库算法并在适当的情况下反转迭代器.例如,

void foo(int i) { /* do stuff */ }

if (smth)
  std::for_each(vec.begin(), vec.end(), foo);
else
  std::for_each(vec.rbegin(), vec.rend(), foo);
Run Code Online (Sandbox Code Playgroud)