2017-02-20 178 views
0

任何人都可以建議如何在C++ 11/14中優雅地迭代一個常量集合(英文意思,而不是C++含義)的數字,最好不要像這樣留下臨時對象:C++:優雅迭代一組數字

set<int> colors; 
colors.insert(0); 
colors.insert(2); 

for (auto color : colors) 
{ 
    //Do the work 
} 

?希望找到1班輪。

換句話說,是否有一個神奇的方式使之顯得有些看起來像這樣:

for (int color in [0,2])//reminds me of Turbo Pascal 
{ 
    //Do the work 
} 

for (auto color in set<int>(0,2))//Surely it cannot work this way as it is 
{ 
    //Do the work 
} 
+1

你正在迭代的是一組整數。迭代使用引用會導致相同或更大的開銷。你有什麼是好的。 –

+0

當你說*這樣的臨時對象*時,你在說什麼對象?例如, –

+0

'for(auto const&color:colors)'是有效的。 –

回答

3

可以使用std::initializer_list代替std::set

for (auto color : {2, 5, 7, 3}) { 
    // Magic 
} 

釷e封閉的大括號{ ... }將推斷出可迭代的std::initializer_list<int>

1

只是一些雜感。 這樣的事情?

for(auto color : set<int>{0, 2}) { // do the work } 

或者可能使用某個函數?

auto worker = [](int x) { // do the work }; 
worker(0); 
worker(2); 

爲了避免臨時對象,也許還可以利用模板函數像

template<int N> 
void worker(params_list) { 
    // do the work 
} 

然後

worker<0>(params_list); 
worker<2>(params_list);