This post will discuss how to convert a map into a vector of pairs in C++. In other words, convert a std::map<int, char> to a std::vector<std::pair<int, char>>.

1. Using copy constructor

An elegant and efficient solution to initialize a vector of pairs with the map entries is using a copy constructor. This solution is simple, short, and efficient. Here’s the sample code:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

 
Since C++17, we can skip the container’s template arguments and have the compiler derive them:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

2. Using std::copy

Another option to copy all elements from a given map to std::vector is using the standard algorithm std::copy from header <algorithm>. This is demonstrated below:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

 
We can use std::copy with std::back_inserter, as shown below:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

3. Using std::vector::assign

The vector::assign member function replaces the current vector elements with the elements in the specified range. It can be used as follows, to convert a map into a vector of pairs:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

 
To avoid overriding any existing values in the vector with the map entries, consider using the vector::insert member function. It is recommended to allocate memory for the vector using the std::vector::reserve function before calling insert, as shown below:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

4. Using Loop

Finally, we can write custom logic for converting a map into a vector of pairs using a range-based for-loop. Here’s what the code would look like:

Download  Run Code

Output:

(1, A)
(2, B)
(3, C)
(4, D)

That’s all about converting a map into a vector of pairs in C++.