简体   繁体   English

按地图排序(Lexicographical Order)

[英]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,cmyComp cmp

  • cmp(a, a) is false. cmp(a, a)是假的。
  • if cmp(a, b) is true, then cmp(b, a) is false. 如果cmp(a, b)为真,则cmp(b, a)为假。
  • if 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.

相关问题 使用 std::string 作为字典顺序的键对 unordered_map 进行排序 - Sorting a unordered_map with a std::string as a key in lexicographical order 非ASCII字符的字典排序 - Lexicographical sorting for non-ascii characters 根据输入值排序std :: map的顺序 - Sorting order of std::map depending on an input value 按字典顺序打印给定字符串的所有字母组合的算法 - Algorithm to print all combination of letters of the given string in lexicographical order 给定一组字符,如何仅通过重新排列字符来显示具有更高字典顺序的字符串? - Given a set of characters, how can you display the string with a higher lexicographical order, only by rearranging the characters? 编写链接函数的更短/更有效的方法,该函数按字典顺序添加新元素 - Shorter/more efficient way of writing a link function that adds new elements in lexicographical order 从字典顺序中获取范围内的下一个数字(不包含所有字符串) - Get next number from range in lexicographical order (without container of all stringifications) 用于排序地图元素的地图比较器 - map comparator for sorting map elements 排序顺序问题 - Sorting order issue 顺序:点排序分析 - Order: An Analysis on Point Sorting
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM