Originally Posted by
tabstop
Keep in mind that
Code:
a_map_s_v_s["hello"].push_back("world");
is doing nothing to the map. You're adding to the
vector a_map_s_v_s["hello"], and therefore you need to be looking at vector::insert, which requires a position to insert into (because vectors are like that -- the ordering has to come from you, not from within).
The suggestion was to build the vector first, then insert the key,value pair, something like
Code:
vector<string> bunch_o_strings;
bunch_o_strings.push_back("one");
bunch_o_strings.push_back("two");
bunch_o_strings.push_back("three);
bunch_o_strings.push_back("world");
a_map_s_v_s.insert(pair("hello", bunch_o_strings));
It might be make_pair instead of pair, because I just typed that into this little box and didn't test it.
Well actually it's inserting an empty vector into the map if the key value "hello" doesn't currently exist in the map, thus no insert is necessary.
I would actually avoid building a vector, and then using insert, because that results in the copying of the vector (in fact potentially twice; Once in building the pair, and once upon inserting that pair).
An improvement would be:
Code:
vector<string> bunch_o_strings;
bunch_o_strings.push_back("one");
bunch_o_strings.push_back("two");
bunch_o_strings.push_back("three");
bunch_o_strings.push_back("world");
a_map_s_v_s["hello"].swap(bunch_o_strings);
The [] operator of the map creates an empty vector and returns that by reference. The vector has a swap method and we use this to exchange the contents of bunch_o_strings and the new empty vector, in constant time. This has the possible added bonus that if there was actually something already mapped from "hello" then it will now be in bunch_o_strings (which might be useful behaviour).
Take a moment to wrap your head around that....
Another possibly even better alternative is to get a reference to the actual vector inside the map (creating it if necessary) and inserting directly into that:
Code:
vector<string> &bunch_o_strings = a_map_s_v_s["hello"];
bunch_o_strings.push_back("one");
bunch_o_strings.push_back("two");
bunch_o_strings.push_back("three");
bunch_o_strings.push_back("world");
This has the possible advantage that if "hello" is already mapped, then all you end up doing is appending further strings into its mapped vector.
insert certainly can be useful at times, but it has negligible advantage here imho.