输入的时候可以使用map来存储,然后将map里的数据转到vector里,按重复数从大到小输出10个即可。
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
using namespace std;
map<string, int> mp;
struct node {
string s;
int num;
node(string s,int num):s(s),num(num){}
};
vector<node> v;
bool cmp(const node&a, const node&b) {
return a.num > b.num;
}
int main() {
int n, m;
string s;
while (cin >> n) {
mp.clear();
for (int i=0; i<n; i++) {
cin >> s;
if (mp.find(s) != mp.end()) {
mp[s] ++;
} else {
mp.insert(make_pair(s, 1));
}
}
v.clear();
map<string,int>::iterator it;
for (it=mp.begin(); it!=mp.end(); it++) {
node x(it->first, it->second);
v.push_back(x);
}
sort(v.begin(), v.end(), cmp);
for (int i=0; i<10; i++) {
cout << v[i].s << endl;
}
}
return 0;
}
原文:http://www.cnblogs.com/marginalman/p/4808888.html