Friday 15 August 2014

c++ - Which is the best way to initialize a std::map whose value is a std :: vector? -



c++ - Which is the best way to initialize a std::map whose value is a std :: vector? -

i have following:

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

to add together new items, following:

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

is there improve way add together value?

thanks

first of all, std::map holds std::pairs of key-value. need insert 1 of these pairs:. second, don't need create temporary vector.

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

you can express above using brace-enclosed initializers:

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

note std::map::insert succeeds if there isn't element same key. if want over-write existing element, utilize operator[]:

container[key] = {value};

c++ c++11 vector map stl

No comments:

Post a Comment