我有这个小程序,它读取一行输入并打印其中的单词,以及它们各自的出现次数.我想根据它们的出现情况对地图中存储这些值的元素进行排序.我的意思是,只出现一次的单词将被命令在开头,然后是出现两次的单词等等.我知道谓词应该返回一个bool值,但我不知道参数应该是什么.它应该是地图的两个迭代器吗?如果有人可以解释这一点,我们将不胜感激.先感谢您.
#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;
}
Run Code Online (Sandbox Code Playgroud)
std::map始终按其键排序.您无法按其值对元素进行排序.
您需要将内容复制到另一个std::vector<std::pair<string, int> >可以排序的数据结构(例如).
这是一个可以用来对这样的a进行排序的谓词vector.请注意,C++标准库中的排序算法需要一个"小于"谓词,它基本上表示"小于b".
bool cmp(std::pair<string, int> const &a, std::pair<string, int> const &b) {
return a.second < b.second;
}
Run Code Online (Sandbox Code Playgroud)