c++遍历方向可变的向量
c++ Iterate through vector with variable direction
我想知道,当输入迭代方向时,是否有人对如何迭代向量(或容器)的元素有任何想法。
这是我能想到的第一件事:
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容器迭代器。我相信还有一个反向迭代器。
相关文章:
- 在遍历处理程序的向量时注册和注销处理程序
- 遍历unordered_map向量
- 如何正确地推回然后遍历堆中对象的向量?
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 执行错误访问 遍历向量
- 尝试重载输出运算符时,我无法遍历对象向量
- 遍历向量与数组哪个更快?
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 遍历包含 c++ 中指针的向量
- 如何遍历地图向量
- 遍历抽象类的向量
- 使用迭代器遍历向量并修改内容
- 遍历向量<向量<对<int, int> > >
- 如何遍历特定字符串的向量
- 循环遍历向量<string>并保持每个元素"count"时出现问题
- 如何使用 c++11 语法创建 for 循环以遍历向量
- 使用 auto 遍历指针的常量向量
- 在C 中的字符串向量的字符串元素中循环遍历所有字符
- 使用另一个向量遍历向量的特定元素