sort a map by Value
-
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
-
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
AFAIK, You can sort maps only by the Key element. I think that is the the point of having maps. Your scenario might work out some way. but what if 2 different keys has the same values? how will you sort it?
Every new day is another chance to change your life.
-
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
NajaR12 wrote:
Can anybody tell me how to sort a map based on the values.
Why do you want to do that? Your desire suggests that you have misunderstood the purpose of a map. The key is supposed to be unique and the value is identified by its corresponding key so you may write code such as in order to retrieve the "box" associated with the
key
:Box& box = Map[key];
However, if your "boxes" are unique you may use them as keys, e.g.:
Map[box1] = key2;
Map[box2] = key4;
Map[box3] = key1;
Map[box4] = key3;Consider using a
std::list
that is entry-sorted."It's supposed to be hard, otherwise anybody could do it!" - selfquote
"High speed never compensates for wrong direction!" - unknown -
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
a map isn't really the right container for this. if you have pairs that need to be sorted, why not put them into a vector/list of
std::pair<key,box>
and sort that onbox
?