2016-02-26 60 views
-7

设r1,r2,r3 ... rn为序列整数。我们想通过所有r值进行如下迭代。C++有以下类型的循环或某种方式来使用模板吗?

foreach r in r1,r2 ... rn。

+0

C++ 11有你想要的东西:基于范围的for循环(http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html)=>'for(auto我:{1,2,3}){...}' – Garf365

+0

谢谢你的作品。你应该已经回答了。 – steviekm3

+2

我不明白普通的'for'循环有什么问题。我假设历史课是欺骗一个字符的限制,这可能表明你没有在这个问题上投入足够的精力。 –

回答

0

您可以使用std :: reference_wrapper以及基于循环的范围。

这里是一个示范项目

#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 
相关问题