This post will discuss how to convert a map to a vector of key-value pairs in C++. In other words, construct a std::vector<std::pair<K,V>> from std::unordered_map<K,V> or std::map<K,V>

1. Using Vector Constructor

The simplest and the most efficient solution is to get the iterators at the beginning and end of the given map, and pass them to the range constructor of the vector class. This will construct a vector of key-value pairs in the same order as present on the map.

Download  Run Code

2. Using std::copy function

If we already have a vector with enough space to hold all the map entries, the recommended solution is to use the standard algorithm std::copy from <algorithm> header. This requires an input range and the output iterator to the destination vector.

Download  Run Code

 
If the destination vector is empty or doesn’t have enough space, we can use std::back_inserter to insert the elements into the container. This works as std::back_inserter calls the push_back() function on the destination container.

Download  Run Code

3. Using std::transform function

Another alternative is to use the std::transform algorithm defined in the <algorithm> header. It applies a given operation to each of the given range elements and stores the result in another range.

Download  Run Code

4. Using std::for_each function

We can also use the std::for_each algorithm that applies the given operation to each element in the given range. To convert a map to a vector of key-value pairs, the range should be iterators at the beginning and end of the given map, and the operation should be push_back() to insert each entry into the vector.

Download  Run Code

5. Using Loop

Finally, we can also iterate the map using a simple for-loop or range-based for-loop (C++11) and insert each entry to the vector, as shown below:

With Iterators

Download  Run Code

Range-based for-loop

Download  Run Code

 
Note: For each of the above solutions using push_back() or a std::back_inserter, consider calling std::vector.reserve() to avoid any re-allocations when the size of the map is large. Also, lambdas (introduced in C++11) can be replaced with a function or an object of a class implementing ()operator.

That’s all about converting a map to a vector of key-value pairs in C++.

 
Exercise: Construct a std::vector<V> from std::unordered_map<K,V>.