[英]Sorting in Map (Lexicographical Order)
the output should be sorted in lexicographically sorted order of names and if two names are same then those are sorted in decreasing order of marks. 输出应按字典顺序排序的名称排序,如果两个名称相同,则按标记的降序排序。
#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;
}
If you want the entries of a map sorted in a particular order (and the default order is operator <
, which doesn't do what you're asking), then you need to instantiate your map with a custom comparator. 如果您希望以特定顺序排序的地图条目(并且默认顺序为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;
Your comparison object should impose a strict weak ordering on the values. 您的比较对象应对值施加严格的弱排序。 That means that for any std::pair<std::string, int> a,b,c
and myComp cmp
: 这意味着对于任何std::pair<std::string, int> a,b,c
和myComp cmp
:
cmp(a, a)
is false. cmp(a, a)
是假的。 cmp(a, b)
is true, then cmp(b, a)
is false. 如果cmp(a, b)
为真,则cmp(b, a)
为假。 cmp(a, b)
is true and cmp(b, c)
is true, then cmp(a, c)
is true. 如果cmp(a, b)
为真且cmp(b, c)
为真,则cmp(a, c)
为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.