map<key, T>, less_key

Aug 2, 2012 at 11:52pm
Hi All,

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
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? Please anyone who knows that tell me how.

Cheers,
Aug 3, 2012 at 12:03am
A_ traverse it backwards (reverse iterators)
1_ use the third template argument, by instance std::greater
\alpha_ don't care
Aug 3, 2012 at 12:36am
The order of a map is something like this (right?):
http://projects.whyaskwhy.org/svn/code_share/beginning_visual_cpp_2008/ch9/Sol9_04/binary_tree.png

In your example, "b" is the root node, "a" is on the left of the "b" node, and "c" is on the right of the "b" node.

The forward iterator simply gives the impression of a linear container, so just use the reverse iterator and you'll be all set.
Last edited on Aug 3, 2012 at 12:38am
Aug 3, 2012 at 12:50am
@ne555 Thank you for your answer, the second method. That's what I exactly need :)

Thank you @LowestOne as well.
Topic archived. No new replies allowed.