哪个是初始化std :: map的最佳方法,它的值是std :: vector?

Jua*_*olo 3 c++ stl vector map c++11

我有以下内容:

std::map<std::string, std::vector<std::string>> container;

要添加新项目,请执行以下操作:

void add(const std::string& value) {
    std::vector<std::string> values;
    values.push_back(value);
    container.insert(key, values);
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来增加价值?

谢谢

jua*_*nza 5

首先,std::map掌握std::pair关键价值.你需要插入其中一对:其次,您不需要制作临时矢量.

container.insert(make_pair(key, std::vector<std::string>(1, value)));
Run Code Online (Sandbox Code Playgroud)

您可以使用支撑封闭的初始化器来表达上述内容:

container.insert({key, {value}});
Run Code Online (Sandbox Code Playgroud)

请注意,std::map::insert只有在没有具有相同键的元素时才会成功.如果要覆盖现有元素,请使用operator[]:

container[key] = {value};
Run Code Online (Sandbox Code Playgroud)