Dynamically sorting both keys and values

Rajput Ankit
1 min readJul 3, 2021

Well, you might have faced this problem in your coding life. Also you might know the answer already. The problem was about the std::map or say std::multimap, both of them are special type of containers who can sort the items by a comparing function pointer(or a built-in one like std::less). They sort it when you are inserting a new item, that’s of course so handy, because you don’t wanna call a sorting function every time you need to! Actually you will never explicitly call any sorting function on your map or multimap, coz it’s already sorted! Now here’s my problem-
Say, I have a map like this -

D - 1
D - 2
B - 3
A - 4

Now I need to sort them like this -

A - 4 
B - 3
D - 2
D - 1

Here’s the explanation of this sorting- first elements(A,B,D) will be sorted in ascending order A → B → D regardless of the second element, secondly if the first elements are equal (i.e 2 Ds here) then they will be sorted as the descending order of their corresponding second element.
Using std::multimap will end-up with only the first sorting part, so I took advantage of templates and inheritances. Here’s the code -

https://gist.github.com/ankitraja786/84967acd0c647770907013d49bcaba1b

And here’s the output -

A	4
B 3
D 2
D 1

--

--

Rajput Ankit

Power corrupts; absolute power corrupts absolutely.