Alex Lee
Alex Lee

Reputation: 171

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

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?

Upvotes: 4

Views: 3895

Answers (2)

beerboy
beerboy

Reputation: 1294

If you have an existing map, and you just want to loop over the elements of a map in reverse, use a 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 << ')';
}

Upvotes: 3

pmr
pmr

Reputation: 59811

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

Upvotes: 10

Related Questions