简体   繁体   English

如何按结构中的属性值对std :: map进行排序

[英]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). std::map始终根据类型(第一个模板参数)进行排序。 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>以便根据计数对数据进行排序(注意,我们确实希望在此处使用multimap ,因为我们可能有多个具有相同计数的char ) 。

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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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