This post will discuss how to convert a vector of pairs to a map in C++.

1. Using std::copy

A simple option to copy all elements from a vector to a map is using the std::copy standard algorithm from header <algorithm>. Its usage is demonstrated below:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

2. Using copy constructor

Alternatively, we can use the copy constructor to initialize a map from the vector of pairs. This is the shortest and the most idiomatic way to convert a vector of pairs to a map. Here’s an example of its usage:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

3. Using std::transform

Another alternative is to use the std::transform algorithm to transform std::vector<std::pair<int, char>> into std::map<int, char>. The std::transform algorithm is defined in the <algorithm> header, and apply a given operation to the specified range and stores the result in another range.

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
We can also use the std::transform algorithm to zip two separate vectors of keys and values together into a map. Here’s what the code would look like:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

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