c++遍历方向可变的向量

c++ Iterate through vector with variable direction

本文关键字:向量 遍历 方向 c++      更新时间:2023-10-16

我想知道,当输入迭代方向时,是否有人对如何迭代向量(或容器)的元素有任何想法。

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

    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
    }

有人知道更好的方法吗?

我会这样做,在适当的时候使用标准库算法和反向迭代器。例如,

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);

有人知道更好的方法吗?

是:只在for循环体中执行操作(荣誉之间的所有内容)。然后,使用std::for_each和一对迭代器。代码经过测试,稳定且惯用:

旧代码:

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

新代码:

auto your_stuff = [](const int& i) { /* do your stuff */ };
// forward iteration:
std::for_each(vec.begin(), vec.end(), your_stuff);
// backward iteration:
std::for_each(vec.rbegin(), vec.rend(), your_stuff);

对于向量来说,您的解决方案非常简洁。在某些数据结构中,这种迭代会过于昂贵,例如单链表。另一方面,您总是可以使用STL容器迭代器。我相信还有一个反向迭代器。