Dave's Brain

Browse - Programming Tips - How do I efficiently copy an STL vector to a STL map?

Date: 2010may14
Language: C/C++
Keywords: Standard Template Library

Q.  How do I efficiently copy an STL vector to a STL map?

A.  There are two "tricks": 
- Reserve the space in advance (for speed)
- Use .first or .second to access the map content

Of course, a map holds a key and a value; and a vector does not.
So you have to decide what you are copying.

The code:

void CopyMapToVector(MYMAP &mymap, MYVECTOR &myvec) { myvec.clear(); // Delete what was in the vector (if anything) // As we mentioned above... reserve the space. Makes it much faster. myvec.reserve(mymap.size()); for (MYMAP::iterator it = mymap.begin(); it != mymap.end(); it++) { // If you want to copy the keys do this: myvec.push_back((*it).first); // Or if you want to copy the values do this: // myvec.push_back((*it).second); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.