根据值和键对键值对进行排序

时间:2020-04-19 12:40:13

标签: c++ overriding stdmap

PS位于以下行: 该报告表包含subject --------- marks。 根据标记按降序对报告进行排序, 如果2个主题的标记相同,则按主题对这2行进行排序,即名称按字母顺序排列的主题排在最前面的主题位于最前面。 什么是解决此PS的好方法? This帮不上忙

我最初尝试覆盖std :: map。但是,试图提供帮助的人们指出,这不是一个好主意。这是我的方法,这也使我对在何处实际分配值?感到困惑:

class map : public std::map<std::string, long, std::greater<>> {
public:
    bool insert(std::pair<std::string, long> pair) {
        //where do I actually "put" the values??
    }
};

我尝试使用

typedef std::function<bool(std::pair<std::string, long>, std::pair<std::string, long>)> compareFunc;
compareFunc compare = [](std::pair<std::string, long> lmark, std::pair<std::string, long> rmarks) {
    if (lmarks.second > rmarks.second)
        return true;
    else if ((lmarks.second == rmarks.second) && (lmarks.first < rmarks.first))
        return true;
    return false;
};
std::set<std::pair<std::string, long>, compareFunc> marks;

但是它在运行时失败

请建议我一个更好的人

1 个答案:

答案 0 :(得分:0)

HackerEarth上也有类似的问题,这就是我如何解决的问题:

#include <algorithm>
#include <iostream> 
#include <vector>

int main() {
    std::vector<std::pair<std::string, long>> hotels;
    long n = 0;
    std::cin >> n;
    while (n--) {
        std::pair<std::string, long> hotel;
        std::cin >> hotel.first >> hotel.second;
        hotels.push_back(hotel);
    }
    std::sort(hotels.begin(), hotels.end(), [](std::pair<std::string, long> lhotel, std::pair<std::string, long> rhotel)->bool {
        if (lhotel.second > rhotel.second)
            return true;
        else if ((lhotel.second == rhotel.second) && (lhotel.first < rhotel.first))
            return true;
        return false;
    });
    std::cout << hotels.front().first;
    return 0;
}

在您的解决方案中,只需使用vector而不是set,一切都会很好:)

仅供参考,如果您想偏离标准的实现 c ++中的任何STL容器,始终要使用向量。永不失败;)