8、sort排序中比较函数的几种应用方式

1、待排序中的元素作数组的下标或map的键值

例题:PAT甲级_1141 PAT Ranking of Institutions

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100010;

struct Node {
    int personNum = 0;
    int scoreB = 0, scoreA = 0, scoreT = 0;
    int score;
};

map<string, Node> mp;
vector<string> ansSchoolName;

bool cmp(string a, string b) {
    if (mp[a].score != mp[b].score) return mp[a].score > mp[b].score;
    else return mp[a].personNum < mp[b].personNum;
}
int main() { int n; scanf("%d", &n); int score; string id, schoolName; for (int i = 0; i < n; i++) { cin >> id >> score >> schoolName; transform(schoolName.begin(), schoolName.end(), schoolName.begin(), ::tolower); mp[schoolName].personNum++; if (id[0] == 'A') mp[schoolName].scoreA += score; else if (id[0] == 'B') mp[schoolName].scoreB += score; else mp[schoolName].scoreT += score; } for (auto it = mp.begin(); it != mp.end(); it++) { ansSchoolName.push_back(it->first); it->second.score = (int)(it->second.scoreA + it->second.scoreB / 1.5 + it->second.scoreT*1.5); } sort(ansSchoolName.begin(), ansSchoolName.end(), cmp); int r = 1; printf("%d", ansSchoolName.size()); for (int i = 0; i < ansSchoolName.size(); i++) { if (i > 0 && mp[ansSchoolName[i]].score != mp[ansSchoolName[i - 1]].score) { r = i + 1; } printf("%d %s %d %d ", r, ansSchoolName[i].c_str(), mp[ansSchoolName[i]].score, mp[ansSchoolName[i]].personNum); } return 0; }
原文地址:https://www.cnblogs.com/fuqia/p/9606830.html