Reverse all key value pairs of a map in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <map> template<typename K, typename V> std::map<V,K> reverseMap(std::map<K,V> const &map) { std::map<V,K> rMap; for (auto const &pair: map) { rMap[pair.second] = pair.first; } return rMap; } int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'} }; std::map<char, int> rMap = reverseMap(map); for (const auto &entry: rMap) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <map> template<typename K, typename V> std::map<V,K> reverseMap(std::map<K,V> const &map) { std::map<V,K> rMap; for (auto it = map.begin(); it != map.end(); ++it) { rMap[it->second] = it->first; } return rMap; } int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'} }; std::map<char, int> rMap = reverseMap(map); for (const auto &entry: rMap) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{A, 1}
{B, 2}
{C, 3}
{D, 4}
C++20 simplifies the range-based for-loop with structured binding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <map> template<typename K, typename V> std::map<V,K> reverseMap(std::map<K,V> const &map) { std::map<V,K> rMap; for (auto const &[k, v] : map) { rMap[v] = k; } return rMap; } int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'D'} }; std::map<char, int> rMap = reverseMap(map); for (const auto &entry: rMap) { std::cout << "{" << entry.first << ", " << entry.second << "}" << std::endl; } return 0; } |
Output:
{A, 1}
{B, 2}
{C, 3}
{D, 4}
That’s all about reversing all key-value pairs of a map in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)