繁体   English   中英

按地图排序(Lexicographical Order)

[英]Sorting in Map (Lexicographical Order)

输出应按字典顺序排序的名称排序,如果两个名称相同,则按标记的降序排序。

#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;
}

如果您希望以特定顺序排序的地图条目(并且默认顺序为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,cmyComp cmp

  • cmp(a, a)是假的。
  • 如果cmp(a, b)为真,则cmp(b, a)为假。
  • 如果cmp(a, b)为真且cmp(b, c)为真,则cmp(a, c)为真。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM