atkayla
atkayla

Reputation: 8849

Sort multimap by values after keys have been sorted

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.

Upvotes: 6

Views: 1958

Answers (2)

Brian Bi
Brian Bi

Reputation: 119219

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.

Upvotes: 6

Paul Evans
Paul Evans

Reputation: 27577

Put your multimap into a set<pair<int, string>>.

Upvotes: 4

Related Questions