1

This works, but is pretty verbose:

for (auto entry : std::vector<std::pair<int, char>>  { {1, 'a'}, {2, 'b'}, {3, 'c'} } ) {
    int num = entry.first;
    char value = entry.second;
    ...
}

There's got to be a more elegant way...

Martin C. Martin
  • 3,565
  • 3
  • 29
  • 36
  • Why does there have to be? Iterating over a container of known type is far more common than iterating over a sequence of literals. – Nicol Bolas Jul 26 '17 at 21:47
  • 1
    This is already a lot more elegant than what we'd have to write to do the same thing a couple of years ago. – Michaël Roy Jul 26 '17 at 21:50
  • 2
    In C++ 17 it should be possible: `for ( auto[num,value] : ...` –  Jul 26 '17 at 21:52
  • Possible duplicate of [How can I emulate destructuring in C++?](https://stackoverflow.com/questions/31394507/how-can-i-emulate-destructuring-in-c) Doesn't help much though. – Carcigenicate Jul 26 '17 at 21:52
  • I can change the `std::vector>` to `std::map` which shortens things a little. Would be nice if there was a way avoid the first / second thing and give meaningful names to them without using two lines, but I'm on C++14 at the moment. – Martin C. Martin Jul 26 '17 at 21:59

1 Answers1

3

In C++11 and later, you can make use of initializer lists to construct a list of pairs:

using std::make_pair;

for (auto x : {make_pair(1, 'a'), make_pair(2, 'b'), make_pair(3, 'c')})
{
    std::printf("%d %c", x.first, x.second);
}

In C++17, it's possible to use structured bindings and class template argument deduction to make it more elegant:

using std::pair;

for (auto [a, b] : {pair(1, 'a'), pair(2, 'b'), pair(3, 'c')})
{
    std::printf("%d %c", a, b);
}
Mário Feroldi
  • 3,463
  • 2
  • 24
  • 49