Click here to Skip to main content
15,885,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,

Can anybody tell me how to sort a map based on the values.
e.g.
Map[key1] = box3;
Map[key2] = box1;
Map[key3] = box4;
Map[key4] = box2;

i want result like,
Map[key2] = box1;
Map[key4] = box2;
Map[key1] = box3;
Map[key3] = box4;

thanks in advance,
RKR
Posted
Updated 25-Jun-12 23:13pm
v2
Comments
[no name] 26-Jun-12 5:10am    
How is the map declared?
Jim Jos 26-Jun-12 5:50am    
MAP is a sorted container and not sure why you want to sort a map on values.. Could you tell me your requirement and we ll be figure out the right data structure for you..
NajaR12 26-Jun-12 6:18am    
Map declaration is as below
map<int, string=""> myMap;

Now Map is sorted based on key but i want to sort based on the value i.e string.
Chandrasekharan P 26-Jun-12 6:22am    
Please don't cross post your questions.
ThatsAlok 27-Jun-12 2:47am    
and what benefits will you get getting sorted data on the base of value. Key will definatly lose it significance!

Provide of a container with the type of the key, and populate the container in the sort order of the values in the map. Thus, you can access the sorted values via the sorted key container. However, you will need to update and resort the key container whenever you modify the map container.

An alternative would be to populate a multipmap container where the values of the map<key_type, val_type> become keys, and the keys become values: multimap<val_type, key_type>.
 
Share this answer
 
v2
I doubt stl::map can help you in above, you asking it to break it basic principle. I believe you have write your own custom data structure for this.

Also, what actually you going to achieve to sort it on the basis of value? if you are going to iterate one by one instead of finding data based on key, better look for other container instead of map
 
Share this answer
 
v2
Comments
NajaR12 29-Jun-12 7:40am    
Thanks for the reply.
Actually key was not significant for me. I used List instead of Map then used the sort() method. my job is done :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900