Technology

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:

#include 
#include 
#include 
#include 
#include 
#include 
void test()
{
    std::map  m;
    std::vector    keys;
    std::vector        values;
    std::transform (keys.begin(), keys.end(),
                    values.begin(),
                    std::inserter (m, m.begin()),
                    std::make_pair);
}

3 thoughts on “Copying a std::vector into a std::map

  1. 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. Oh, I’m sorry, a little correction:
    std::vector v;
    std::multimap mm;
    in the code above.

  3. 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;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.