C++是否有以下类型的 for 循环或某种使用模板的方法

Does C++ have following type of for loops or some way to do it with templates?

本文关键字:方法 循环 是否 for 类型 C++      更新时间:2023-10-16

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