使用优先队列构建最小堆,不用使用vector数组再排序,
优先队列详解(优先队列和queue
不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队,优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的)
#include "stdafx.h"
#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<vector>
using namespace std;
map<string, int>mp;
struct node {
string s;
int num;
node(string s=NULL,int num=0):s(s),num(num){}
};
struct cmp {
bool operator ()(const node&a, const node&b)const
{
return a.num > b.num;
}
};
priority_queue <node, vector<node>, cmp> pq;//优先队列,默认最大顶堆,这里构建小堆
int main()
{
int n, m, i;
string s;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> s;
if (mp.find(s) != mp.end())
mp[s]++;
else
mp.insert(make_pair(s, 1));
}
map<string, int>::iterator it;
for (it = mp.begin(), i = 0; it != mp.end();it++, i++)
{
if (i < 10)
{
node x(it->first, it->second);
pq.push(x);
}
else
{
node x(it->first, it->second);
if (it->second > pq.top().num)
{
pq.pop();
pq.push(x);
}
}
}
while (!pq.empty())
{
cout << pq.top().s << endl;
pq.pop();
}
return 0;
}