I want to initialize a std::map
object with keys contained in a std::vector
object.
std::vector<char> mykeys { 'a', 'b', 'c' ];
std::map<char, int> myMap;
How can I do that without a loop?
And can I add a default value to my int
?
Without an explicit loop:
std::transform( std::begin(mykeys), std::end(mykeys),
std::inserter(myMap, myMap.end()),
[] (char c) {return std::make_pair(c, 0);} );
Demo.
A range-based for loop would be far more sexy though, so use that if possible:
for (auto c : mykeys)
myMap.emplace(c, 0);
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