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
First of all, std::map
holds std::pair
s 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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With