Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is 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 the value?

Thanks

like image 337
Juan Solo Avatar asked Dec 26 '22 03:12

Juan Solo


1 Answers

First of all, std::map holds std::pairs of key-value. You need to insert one of these pairs:. Second, you don't need to make a temporary vector.

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

You can express the above using brace-enclosed initializers:

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

Note that std::map::insert only succeeds if there isn't already an element with the same key. If you want to over-write an existing element, use operator[]:

container[key] = {value};
like image 180
juanchopanza Avatar answered Mar 07 '23 15:03

juanchopanza