按地图排序(按字典顺序)

时间:2019-06-22 22:10:01

标签: c++ stl

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

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

1 个答案:

答案 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,cmyComp cmp

  • cmp(a, a)是错误的。
  • 如果cmp(a, b)为true,则cmp(b, a)为false。
  • 如果cmp(a, b)为真且cmp(b, c)为真,则cmp(a, c)为真。