首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >按值对地图进行排序.键

按值对地图进行排序.键
EN

Stack Overflow用户
提问于 2022-05-28 17:03:47
回答 2查看 59关注 0票数 0

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

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

限制:我只能使用像<iostream>**,** <map>**,** <string>**,** <fstream> <utility>这样的标题

它应该如何工作的例子:

在:

代码语言:javascript
运行
复制
one two three one two four two one two

退出:

代码语言:javascript
运行
复制
four 1
three 1
one 3
two 4

到现在为止,我已经做了这样的事情:

代码语言:javascript
运行
复制
#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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-28 17:22:49

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

代码语言:javascript
运行
复制
#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";
  }
}
票数 0
EN

Stack Overflow用户

发布于 2022-05-28 17:54:53

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

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72417624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档