输出应按名称的字典顺序排列,如果两个名称相同,则按标记的降序排列。
#include <iostream>
#include <map>
#include <tuple>
int main() {
int t;
std::cin >> t;
while(t--) {
int n;
std::cin >> n;
std::string name;
int marks;
std::map<std::pair<std::string, int>, int> hash;
for(int i = 0; i < n; i++) {
std::cin >> name >> marks;
std::pair<std::string, int> p;
p.first = name;
p.second = marks;
hash[p]++;
}
for(auto it = hash.begin(); it != hash.end(); ++it) {
std::cout << (it->first).first << " " << (it->first).second << " "
<< it->second << "\n";
}
}
return 0;
}
答案 0 :(得分:3)
如果您希望地图的条目按特定顺序排序(默认顺序为operator <
,这与您的要求不符),则需要使用自定义实例化地图比较器。
struct myComp {
bool operator()(const std::pair<std::string, int>& lhs,
const std::pair<std::string, int>& rhs) const
{ /* your code here */ }
};
std::map<std::pair<std::string, int>, int, myComp> m;
您的比较对象应该对值施加严格的弱排序。
这意味着对于任何std::pair<std::string, int> a,b,c
和myComp cmp
:
cmp(a, a)
是错误的。cmp(a, b)
为true,则cmp(b, a)
为false。cmp(a, b)
为真且cmp(b, c)
为真,则cmp(a, c)
为真。