Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range-based for over pair list

Tags:

c++

c++11

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}})
    // ...

?

like image 810
IceFire Avatar asked Sep 18 '17 14:09

IceFire


People also ask

What is a ranged based for loop?

Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).

How do you define a range in CPP?

Remarks. Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .

What does auto do in a for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.


Video Answer


2 Answers

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.

like image 90
StoryTeller - Unslander Monica Avatar answered Sep 20 '22 06:09

StoryTeller - Unslander Monica


The good ol' type alias:

using pairlist = std::initializer_list<std::pair<int,int>>;

for(auto pair : pairlist{{1,2}, {3,4}})
{
    // stuff happens here
}
like image 31
Galik Avatar answered Sep 19 '22 06:09

Galik