2016-02-26 55 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 
相關問題