map的按值排序 输出出现次数最多的字符串

using namespace std;
typedef pair<string, int>Pair;

bool cmp(const Pair&a, const Pair&b) {
	return a.second > b.second;//大顶
}

int main() {
	int n;
	while (~scanf("%d", &n) && n) {
		vector<Pair>PairVec;
		map<string, int>m;
		for (int i = 0;i < n;i++) {
			string c;
			cin >> c;++m[c];//插入键  值默认为0(作为计数器)
		}
		for (map<string, int>::iterator it = m.begin();it != m.end();++it) {
			PairVec.push_back(make_pair(it->first, it->second));
		}
		sort(PairVec.begin(), PairVec.end(), cmp);
		cout << PairVec.front().first << endl;
	}
	//此处map是按照键string排序(字典序) 无法直接对map操作来完成按值排序
	//完成此操作需要把map的每个元素make_pair然后压入vector
	//通过对pair<string,int>的cmp函数完成按值排序,然后输出vector中的第一项
	//即为出现次数最多的字符串
}

猜你喜欢

转载自blog.csdn.net/hanker99/article/details/84076014
今日推荐