按值排序地图 - 键

Sorting a map by values - keys

我正在编写一个代码来计算文件中每个单词的出现次数,并按出现次数的顺序打印出这些单词。在每个单词之后,它会打印出现的次数。文件中出现次数相同的单词按字母顺序列出。

我不知道如何修改该代码以按出现次数的顺序获取单词,并且文件中出现相同次数的单词按字母顺序列出。

限制:我只能使用 headers,例如 <iostream><map><string><fstream><utility>

它应该如何工作的示例:

在:

one two three one two four two one two

输出:

four 1
three 1
one 3
two 4

到目前为止,我已经做过类似的事情了:

#include <iostream>
#include <fstream>
#include <map>
#include <string>
typedef std::map<std::string, int> StringIntMap;

void count_words(std::istream &in, StringIntMap &words)
{
    std::string text;
    while (in >> text)
    {
        ++words[text];
    }
}

int main(int argc, char **argv)
{
    std::ifstream in("readme.txt");
    StringIntMap words_map;
    count_words(in, words_map);

    for (StringIntMap::iterator it = words_map.begin(); it != words_map.end(); ++it)
    {
        std::cout << it->first << " " << it->second << std::endl;
    }
}

使用std::map 执行排序的解决方案。 通过将 std::pair<string, int> 替换为具有有意义名称的结构,可以进一步提高可读性。

#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <utility>

using std::cout;
using std::ifstream;
using std::map;
using std::pair;
using std::string;

struct Dummy {};

struct Compare {
  bool operator()(const pair<string, int> &p1,
                  const pair<string, int> &p2) const {
    if (p1.second < p2.second) {
      return true;
    } else if (p1.second > p2.second) {
      return false;
    } else {
      return p1.first < p2.first;
    }
  }
};

int main(int argc, char **argv) {
  ifstream in("readme.txt");

  map<string, int> occurences;
  string word;
  while (in >> word) {
    occurences[word]++;
  }

  map<pair<string, int>, Dummy, Compare> sorted;
  for (const auto &p : occurences) {
    sorted.insert({p, Dummy{}});
  }
  for (const auto &p : sorted) {
    cout << p.first.first << ": " << p.first.second << "\n";
  }
}

您可以使用 std::multimap 进行排序。

int main()
{
    std::map<std::string,int> words_map;
    count_words(std::cin, words_map);
    
    std::multimap<int,std::string> frequency_map;

    for(auto& [word,freq]:words_map){
        frequency_map.insert({freq,word});
    }

    for(auto& [freq,word]:frequency_map){
        std::cout << word << ' ' << freq << '\n';
    }
}

https://godbolt.org/z/Er7o8Wec1