Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the ordering of a std::map to be reversed?

Tags:

c++

map

Does anyone know that is there a way that I can change the map order from less to kind of "more"?

For example:

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

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

Inside the map, 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 that in a easy way?

like image 522
Alex Lee Avatar asked Dec 12 '22 23:12

Alex Lee


1 Answers

By using std::greater as your key instead of std::less.

e.g.

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

See the reference

like image 151
pmr Avatar answered Dec 14 '22 11:12

pmr