Range for more than two pairs

Let's say I want to repeat a series of pairs defined on a line. Is there a shorter way to write:

for(auto pair : std::initializer_list<std::pair<int,int>>{{1,2}, {3,4}}) // ... 

?

+7
c ++ c ++ 11
source share
2 answers

Just indicate the first element - this is a pair. The rest will be displayed automatically:

 for(auto& pair : {std::pair<int,int>{1,2}, {3,4}}) ; 

The entered closed initializer is displayed as std::initalizer_list , and the first element, called a pair, will require that all elements be an initializer for the pair.

You noted C ++ 11, but for completeness it can be even shorter in C ++ 17:

 for(auto& pair : {std::pair{1,2}, {3,4}}) ; 

Due to the output of the template template argument. If you don't have this, std::make_pair will work if you want to preserve the benefits of template argument output:

 for(auto& pair : {std::make_pair(1,2), {3,4}}) ; 

Although supposedly it is not as useful for playing golf as the C ++ version 17.

+9
source share

Good ol 'type alias:

 using pairlist = std::initializer_list<std::pair<int,int>>; for(auto pair : pairlist{{1,2}, {3,4}}) { // stuff happens here } 
+1
source share

All Articles