How to sort map based on its values

Jan 17, 2009 at 4:33pm
I have defined a map<string, int> where string are words and int are how many times they appear in a textfile.

Now I want to sort the according to descending order of it's frequency. I now for this I have to write my own comparison function, which will be use in sort.


But I am finding difficulty in this So I need help.... Thanks in advance
Jan 17, 2009 at 8:34pm
google for a bubble sort example.
Jan 18, 2009 at 3:24am
Go to the page on here about the map's constructor.
Jan 18, 2009 at 5:57pm
Use a multimap of <int, string>.

Iterate through the original map, make_pair of <int, string>, and insert into the multimap.

The default multimap less sorts in ascending order. You can iterate through the multimap in reverse order.

Jiryih Tsaur
Jan 18, 2009 at 8:05pm
If you want a container in which you want to be able to sort on both key and value, the right container is a boost::multi_index_container. However, boost isn't for the faint of heart, and if this for a school project, then do as jtsaur said.

Topic archived. No new replies allowed.