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};
With intializer lists (C++11), you could just do container.insert({key, { value }});
where {value}
will build a std::vector
and {key, {value}}
will build a std::pair
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.