Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map initialization with a std::vector

Tags:

c++

c++11

stl

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?

like image 569
hao Avatar asked Nov 30 '22 18:11

hao


1 Answers

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);
like image 192
Columbo Avatar answered Dec 25 '22 17:12

Columbo