Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say, I want to iterate a number of pairs defined inline. Is there a shorter way to write:

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

?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
827 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just specify the first element is a pair. The rest will be deduced automatically:

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

The braced enclosed initializer is deduced to be std::initalizer_list, and the first element being named a pair will require all elements to be an initalizer for a pair.

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

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

Due to class template argument deduction. If you don't have that, than std::make_pair will do if you want to maintain the benefits of template argument deduction:

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

Though ostensibly, it isn't as useful for code golfing as the C++17 version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...