Home > other >  How to iterate over temporary pairs
How to iterate over temporary pairs

Time:04-11

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related