简体   繁体   中英

How to sort std::map by property value in struct

I have a struct like this...

struct MessageLetter{
 char letter;
 int count;
 MessageLetter() {}
 MessageLetter(char letter, int count)
 : letter(letter), count(count)
 {}
};

I use it to create the following map...

std::map<char, MessageLetter> lList;

I would like to sort it, something like this for a list...

bool compare_count(const MessageLetter& first, const MessageLetter& second){
  if(first.count > second.count){
   return true;
  }
  return false;
}

How would I do this? Would I need to use something like...

bool compare_count(const std::pair <char,MessageLetter>& first, const const std::pair <char,MessageLetter>& second)

You have a fairly basic problem here. An std::map is always sorted based on the key type (the first template parameter). You want sorting based on the second parameter (the value). That's simply not supported.

From the looks of things, what you're trying to do is to count up the frequencies of characters in a message, then write them out in descending order by frequency.

If so, you really need (or at least want) to do things in three steps: first count up the frequencies, then sort by frequency, and finally print out the sorted data.

For the first step, I'd just use a vector:

unsigned max = std::numeric_limits<unsigned char>::max();

std::vector<unsigned> counts(max);

while (infile >> ch)
    ++counts[(unsigned char)ch];

Then I'd probably copy that data to an std::multimap<unsigned, char> to get it sorted based on the count (and note we do want a multimap here, because we might have more than one char with the same count).

std::multimap<unsigned, char> frequencies;
typedef std::pair<unsigned, char> v_t;

for (unsigned char i=0; i<max; i++)
    frequencies.insert(std::make_pair(i, counts[i]));

Finally, write out the result in descending order by frequency:

std::copy(frequencies.rbegin(), frequencies.rend(), 
          std::ostream_iterator<v_t>(std::cout, "\n"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM