views:

289

answers:

4

Hi

I wonder how can I implement the STL map sorting by value.

For example, I have a map m

map<int, int>;
m[1] = 10;
m[2] = 5;
m[4] = 6;
m[6] = 1;

and then.. I'd like to sort that with the m's value. So, if I print the map, I'd like to get the result like

m[6] = 1
m[2] = 5
m[4] = 6
m[1] = 10

this.

How can I sort like this way? Is there any way that I can deal with the key and value with sorted values?

+3  A: 

I wonder how can I implement the STL map sorting by value.

You can’t, by definition. A map is a data structure that sorts its element by key.

Konrad Rudolph
How can I implement this function? I need this function.
Charlie Epps
@Charlie Epps : With another map? Each time you add a key/value to the first map, you add a value/key to the second...
paercebal
+1  A: 

You should use Boost.Bimap for this sort of thing.

rlbond
... provided your mapping is one-to-one.
Vlad
Actually, Boost.Bimap supports non-one-to-one operations. For example, `bimap<multiset_of<int>, set_of<double> >`
rlbond
+6  A: 

You can build a second map, with the first map's values as keys and the first map's keys as values.

swegi
haha, may be the perfect solution.
Charlie Epps
Only if your values are all distinct. :-P
Chris Jester-Young
if not, use a multimap.
swegi
+8  A: 

Dump out all the key-value pairs into a set<pair<K, V> > first, where the set is constructed with a less-than functor that compares the pair's second value only. That way, your code still works even if your values aren't all distinct.

Or dump the key-value pairs into a vector<pair<K, V> >, then sort that vector with the same less-than functor afterwards.

Chris Jester-Young
perfect approach
Charlie Epps