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