This post will discuss how to reverse all key-value pairs of a map in C++. The values in the map may or may not be unique.

The idea is to create a new instance of std::map<V,K> for the map of type std::map<K,V>. Then loop over the map and insert each key-value pair into the new map in reverse order, as shown below:

Download  Run Code

Output:

{A, 1}
{B, 2}
{C, 3}
{D, 4}

 
The above code assumes that the reverse mapping is well-defined. Otherwise, any repeated values in the map will override the previous values. The range-based for-loop may be replaced with the iterator-based for-loop:

Download  Run Code

Output:

{A, 1}
{B, 2}
{C, 3}
{D, 4}

 
C++20 simplifies the range-based for-loop with structured binding.

Download Code

Output:

{A, 1}
{B, 2}
{C, 3}
{D, 4}

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