【问题标题】:How can I sort a map with a pair as a key in reverse order?如何以相反的顺序对以一对作为键的地图进行排序?
【发布时间】:2015-03-06 15:38:05
【问题描述】:

我有一张地图

map< std::pair<double, long>, object > myMap;

基本上我希望它按那对排序。如何对其进行排序,以便我的double 是降序排列,而我的 long 是升序排列。

所以通常在插入时我会得到({3.2, 5}, {3.2, 6}, {4, 1}),但我想要的是得到({4, 1}, {3.2, 5}, {3.2, 6})。我想我可以开始考虑我自己的算法,但我希望有一种方法可以让 map 让你用std::greater 反向排序。有什么建议吗?

【问题讨论】:

  • 你看过at the documentation 吗? (提示提示:模板参数)
  • 写自己的函子有什么问题?
  • “而不是编写我自己的排序算法”你根本不是在编写算法你只是在编写一个微不足道的比较函数。如果您使用了不同的类型而不是对 id 告诉您重载 operator> 这是 AFAIK std::greater 调用的内容。

标签: c++ sorting dictionary stl


【解决方案1】:

没有标准的比较器可以满足您的需求。提供您自己的比较器,它会给出您想要的顺序:

typedef std::pair<double, long> key; // for convenience

struct compare_keys {
    bool operator()(key const & lhs, key const & rhs) {
        if (lhs.first < rhs.first) return false;
        if (rhs.first < lhs.first) return true;
        return lhs.second < rhs.second;
    }
};

并使用第三个(可选)模板参数来指定这个而不是std::less

std::map<key, object, compare_keys> myMap;

您可以通过比较修改后的对来稍微缩短(并且可以说是混淆):

return std::make_pair(-lhs.first, lhs.second) 
     < std::make_pair(-rhs.first, rhs.second);

【讨论】:

  • 我认为tie 不会起作用。 -lhs.first 不是左值。
  • 哦,键的负数很好,因此它的顺序相反。我喜欢!
猜你喜欢
  • 2014-11-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 2015-11-07
相关资源
最近更新 更多