'How to iterate over temporary pairs

I would like to loop over an array of temporary pairs (with specifying as few types as possible)

for (const auto [x, y] : {{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}

Is that possible? (I am free to use any C++ standard which is implemented in gcc 11.2)

Currently I am using a workaround using maps which is quite verbose

for (const auto [x, y] : std::map<int, double>{{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}


Solution 1:[1]

std::map performs a heap allocation, which is a bit wasteful. std::initializer_list<std::pair<int, double>> is better in this regard, but more verbose.

A bit saner alternative:

for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}})

Note that in this case the type of the first element dictates the types of the remaining elements. E.g. if you do {std::pair{1, 2}, {3.1, 4.1}}, the last pair becomes {3,4}, since the first one uses ints.

Solution 2:[2]

As a minimal solution, you can iterate over a std::initializer_list of std::pairs by explicitly making at least one element of the initializer list a std::pair:

for (const auto [x, y] : {std::pair{1, 1.0}, {2, 1.1}, {3, 1.2}}) {
  // ...
}

Demo on godbolt.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HolyBlackCat
Solution 2 Brian