I'm trying to do something like this:
const std::map<char, int> histogram{
{'A', 2},
{'D', 1},
{'M', 1},
};
for (const auto& [index, key, value] : std::views::enumerate(histogram))
{
// ...
}
but it doesn't compile (Compiler Explorer) reporting error:
<source>:13:21: error: 3 names provided for structured binding
13 | for (const auto& [index, key, value] : std::views::enumerate(histogram))
| ^~~~~~~~~~~~~~~~~~~
<source>:13:21: note: while 'const std::tuple<long int, const std::pair<const char, int>&>' decomposes into 2 elements
Naively using [index, [key, value]] of course didn't work either...
Is there some other trick I'm missing or in this case I just cannot "unpack" the map element and instead have to keep it like [index, entry] and then use entry.first and entry.second?
Or maybe <ranges> offers something else than enumerate for this scenario?
Structured binding can "unpack" only a single level - in your case it would be to the index and entry in the map.
You can solve it by adding a second structured binding to "unpack" the entry in the map:
for (const auto& [index, entry] : std::views::enumerate(histogram))
{
// Second binding:
const auto& [key, value] = entry;
std::cout << "index: " << index << ", key: " << key << ", value: " << value << '\n';
}
Output:
index: 0, key: A, value: 2
index: 1, key: D, value: 1
index: 2, key: M, value: 1
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With