使用std :: vector初始化std :: map

hao*_*hao 2 c++ stl c++11

我想用std::map对象中包含的键初始化std::vector对象.

std::vector<char> mykeys { 'a', 'b', 'c' ];
std::map<char, int> myMap;
Run Code Online (Sandbox Code Playgroud)

如果没有循环,我怎么能这样做?

我可以为我添加默认值int吗?

Col*_*mbo 12

没有显式循环:

std::transform( std::begin(mykeys), std::end(mykeys),
                std::inserter(myMap, myMap.end()),
                [] (char c) {return std::make_pair(c, 0);} );
Run Code Online (Sandbox Code Playgroud)

演示.

基于范围的for循环会更加性感,所以尽可能使用它:

for (auto c : mykeys)
    myMap.emplace(c, 0);
Run Code Online (Sandbox Code Playgroud)