Reverse keys in a Map

How can I reverse keys in a Map? For example:

"Key 1" - "Value 1"
"Key 2" - "Value 2"
"Key 3" - "Value 3"

To

"Key 3" - "Value 1"
"Key 2" - "Value 2"
"Key 1" - "Value 3"

How can I accomplish this?
The key ordering is defined by the map's type, so you can't change the ordering of a map. What you can do is create a new map of a different type that orders the keys differently.

1
2
3
4
5
6
7
8
9
std::map<std::string, std::string> map;
map["key1"] = "value1";
map["key2"] = "value2";
map["key3"] = "value3";
std::map<std::string, std::string, std::greater> reversed_map;
for (auto &kv : map)
    reversed_map[kv.first] = kv.second;
for (auto &kv : reversed_map)
    std::cout << kv.first << " - " << kv.second << std::endl;
Reversing the associated values is equivalent to reversing the keys. Reverse the values in a map:
1
2
3
auto first = map.begin(), last = map.end() ;
using std::swap ;
for( ; ( first != last ) && ( first != --last ) ; ++first ) swap( first->second, last->second ) ;

http://coliru.stacked-crooked.com/a/d481fbe6eef2fd8c
Last edited on
Thanks!
Topic archived. No new replies allowed.