gpt4 book ai didi

c++ - 从 string 到 int 的映射的谓词

转载 作者:太空宇宙 更新时间:2023-11-04 15:09:29 25 4
gpt4 key购买 nike

我有这个小程序,它读取一行输入并打印其中的单词,以及它们各自的出现次数。我想根据它们的出现对存储这些值的 map 中的元素进行排序。我的意思是,只出现一次的单词将排在开头,然后是出现两次的单词 7,依此类推。我知道谓词应该返回一个 bool 值,但我不知道参数应该是什么。它应该是 map 的两个迭代器吗?如果有人可以解释这一点,将不胜感激。提前谢谢你。

#include<iostream>
#include<map>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::map;

int main()
{
string s;
map<string,int> counters; //store each word & an associated counter

//read the input, keeping track of each word & how often we see it
while(cin>>s)
{
++counters[s];
}

//write the words & associated counts
for(map<string,int>::const_iterator iter = counters.begin();iter != counters.end();iter++)
{
cout<<iter->first<<"\t"<<iter->second<<endl;
}

return 0;
}

最佳答案

std::map始终根据其键排序。您不能按元素的值对元素进行排序。

您需要将内容复制到另一个可以排序的数据结构(例如 std::vector<std::pair<string, int> > )。

这是一个谓词,可用于对这样的 vector 进行排序.请注意,C++ 标准库中的排序算法需要一个“小于”谓词,基本上表示“小于 b”。

bool cmp(std::pair<string, int> const &a, std::pair<string, int> const &b) {
return a.second < b.second;
}

关于c++ - 从 string 到 int 的映射的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4923108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com