How to change the sort order of std :: map?

Does anyone know that there is a way that I can change the order of the cards from smaller to a kind of "bigger"?

For instance:

There is a map<string, int> called test . I insert several entries into it:

 test["b"] = 1; test["a"] = 3; test["c"] = 2; 

Inside the card, the order will be (a, 3)(b, 1)(c, 2) .

I want it to be (c, 2)(b, 1)(a, 3) .

How can I do this in a simple way?

+4
source share
2 answers

Using std::greater as your key instead of std::less .

eg.

 std::map< std::string, int, std::greater<std::string> > my_map; 

See link

+9
source

If you have an existing map, and you just want to iterate over the map elements in reverse order, use the reverse iterator:

 // This loop will print (c, 2)(b, 1)(a, 3) for(map< string, int >::reverse_iterator i = test.rbegin(); i != test.rend(); ++i) { cout << '(' << i->first << ',' << i->second << ')'; } 
+2
source

All Articles