Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort multimap by values after keys have been sorted

Tags:

c++

multimap <int, string> mm; 

(1, A),
(2, B),
(3, D),
(3, C)

I was able to get some data in numerical order using multimap keys, but in the case of duplicates, I would like the values to be in order as well.

(1, A),
(2, B),
(3, C),
(3, D)

What's the easiest way of doing this? Seeing as to how maps only sort by key, I would think I would have to make a set of some sort, but am not sure how to proceed.

like image 819
atkayla Avatar asked Mar 21 '23 18:03

atkayla


1 Answers

There are two reasonable solutions---pick the one that makes more sense.

If you view the int as a key and the string as a value, but a key can be mapped to multiple values---in other words, if you view two pairs with the same int as being part of the same "group" and you might want to iterate through a specific group easily, then use a map<int, multiset<string> >.

If you view each int, string pair as distinct, and some pairs just might happen to have the same int, then you want a multiset<pair<int, string> >.

In the case that duplicate pairs (both int and string are the same) should not be present, these become map<int, set<string> > and set<pair<int, string> > respectively.

like image 180
Brian Bi Avatar answered Mar 23 '23 08:03

Brian Bi