What's the best way to initialize a std :: map whose value is a std :: vector?

I have the following:

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

To add new items, I do the following:

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

      

Is there a better way to add value?

thank

+3


source to share


2 answers


First of all, it std::map

contains std::pair

the key values. You need to insert one of these pairs :. Second, you don't need to create a temporary vector.

container.insert(make_pair(key, std::vector<std::string>(1, value)));

      

You can express this using parenthesized initializers:



container.insert({key, {value}});

      

Note that std::map::insert

only works if there is no element with the same key yet. If you want to overwrite an existing item, use operator[]

:

container[key] = {value};

      

+4


source


With initializer lists (C ++ 11), you can just do container.insert({key, { value }});

where {value}

to build std::vector

and where {key, {value}}

to build std::pair

.



+4


source







All Articles