Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ STL
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 26-Jun-12 0:01am
NajaR12329
Edited 26-Jun-12 0:13am
v2
Comments
pwasser at 26-Jun-12 5:10am
   
How is the map declared?
JimJos at 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 at 26-Jun-12 6:18am
   
Map declaration is as below
map myMap;
 
Now Map is sorted based on key but i want to sort based on the value i.e string.
Chandrasekharan P at 26-Jun-12 6:22am
   
Please don't cross post your questions.
ThatsAlok at 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!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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>.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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
  Permalink  
v2
Comments
NajaR12 at 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)

  Print Answers RSS
0 Maciej Los 315
1 OriginalGriff 273
2 Aajmot Sk 224
3 Marcin Kozub 210
4 Richard MacCutchan 200
0 OriginalGriff 7,853
1 Sergey Alexandrovich Kryukov 7,107
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,790


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 27 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100