What would a std::map extended initializer list look like?
73,966
I'd like to add to doublep's answer that list initialization also works for nested maps. For example, if you have a std::map
with std::map
values, then you can initialize it in the following way (just make sure you don't drown in curly braces):
int main() {
std::map<int, std::map<std::string, double>> myMap{
{1, {{"a", 1.0}, {"b", 2.0}}}, {3, {{"c", 3.0}, {"d", 4.0}, {"e", 5.0}}}
};
// C++17: Range-based for loops with structured binding.
for (auto const &[k1, v1] : myMap) {
std::cout << k1 << " =>";
for (auto const &[k2, v2] : v1)
std::cout << " " << k2 << "->" << v2;
std::cout << std::endl;
}
return 0;
}
Output:
1 => a->1 b->2
3 => c->3 d->4 e->5
Author by
rubenvb
Be sure to check out my github, and ResearchGate profiles which show most of what I do that might be professionally relevant.
Updated on September 19, 2020Comments
-
rubenvb over 3 years
If it even exists, what would a
std::map
extended initializer list look like?I've tried some combinations of... well, everything I could think of with GCC 4.4, but found nothing that compiled.