Pete Ware

Tech, NYC & Politics

Copying a std::vector into a std::map

I had two vector’s with the first being the keys and the second being the values. It took a couple tries before I got the STL working for me!

The first thing was to check if the std::map constructors had something useful. It certainly seems like taking two sets of iterators would be a great way to initialize a map. No such luck.

So how about one of the std algorithms to copy the keys and values into the map? std::copy seemed likely but it only takes a single sequence. A little more digging and std::transform. The second version of std::transform takes two sequences, an output iterator, and a binary function to convert the two values from the two sequences into something that can be inserted into the output iterator. Perfect.

So how to turn the two values into a pair suitable for std::map? The std::make_pair
is exactly what is needed. The hard part is getting the syntax so you can pass it as a function: make_pair in this example.

So the code finally looks like:

3 Comments

  1. Narek Khachatryan

    April 8, 2014 at 5:18 pm

    Hi, i have exactly the same situation and did almost exactly the same way as you, but it does’nt work in MS Visual Studio 2010 :(, later tried your way by creating the vector of values, but got the same result. I will show as i have done (headers are exactly the same):

    std::vector v;
    std::multimap mm;
    std::transform (v.begin (), v.end (), std::inserter(mm, mm.begin ()),
    std::bind2nd (std::make_pair, 0));

  2. Narek Khachatryan

    April 8, 2014 at 5:21 pm

    Oh, I’m sorry, a little correction:
    std::vector v;
    std::multimap mm;

    in the code above.

  3. Narek Khachatryan

    April 8, 2014 at 5:26 pm

    this editor is deleting template arguments interpreting as tags and ignoring), i will try this way 🙂

    std::vector < std::string > v;
    std::multimap < std::string, unsigned > mm;

Comments are closed.

© 2017 Pete Ware

Theme by Anders NorenUp ↑