C++是否有以下类型的 for 循环或某种使用模板的方法
Does C++ have following type of for loops or some way to do it with templates?
Let r1,r2,r3 ...rn 是序列整数。 我们希望按如下方式遍历所有 r 值。
对于 r1,r2 中的每个 r ...RN.
c++11 有你想要的东西:基于范围的 for 循环 (http://cprogramming.com/c++11/c++11-ranged-for-loop.html) => for(auto i: { 1, 2, 3 }) { ... }
您可以使用 std::reference_wrapper 以及基于范围的 for 循环。
这是一个演示程序
#include <iostream>
#include <functional>
int main()
{
int a = 0;
int b = 1;
int c = 2;
for ( auto x : { a, b, c } ) std::cout << x << ' ';
std::cout << std::endl;
int i = 10;
for ( auto r : { std::ref( a ), std::ref( b ), std::ref( c ) } ) r.get() = i++;
for ( auto x : { a, b, c } ) std::cout << x << ' ';
std::cout << std::endl;
}
它的输出是
0 1 2
10 11 12
相关文章:
- 方法内部但循环仍得到预期的不合格id错误C++
- 在 c++ 中实现嵌套循环的更短方法吗?
- 如何在C++中循环访问未知对象方法?
- EnQueue 方法在循环队列中未正确返回C++?
- C++模板方法中的循环依赖关系
- 为什么这种方法会进入无限循环?
- 编写按初始值循环的循环的更好方法是什么
- 循环遍历标准的正确方法::array<char*, N>
- 类方法 - 数据结构中 For 循环的运行时错误
- 循环依赖,在继承类的情况下使用覆盖方法
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
- 还有其他方法可以为乘法表编写循环以获取运行时值吗?
- 如何避免模板方法的循环依赖
- 使用虚拟变量对 std::vector 内部循环进行切片的最佳方法
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- 我应该避免在循环中重复访问相同的方法吗?
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP