如何使地图按值C ++排序

问题描述 投票:0回答:1

[我试图使用自定义比较器按值对地图进行排序,但我无法弄清楚为什么不断收到“没有对compareByVal的匹配调用的错误]

这是我的main.cpp中的内容:

#include <map>
#include <iostream>

struct compareByVal {
  bool operator[](const std::pair<int,int> & a, const std::pair<int,int> & b)
    return a.second < b.second;
}

int main() {
  std::map<int,int,compareByVal> hash;
  hash[1] = 5;
  hash[2] = 2;
  hash[3] = 10;

  std::cout << hash.begin()->first << std::endl;
}
c++ dictionary comparator
1个回答
1
投票

第一个简单的问题是

struct compareByVal {
  bool operator[](const std::pair<int,int> & a, const std::pair<int,int> & b)
    return a.second < b.second;
}

应该是

struct compareByVal {
  bool operator()(const std::pair<int,int> & a, const std::pair<int,int> & b) const {
    return a.second < b.second;
  }
};

第二个严重的问题是比较的签名错误。应该是

struct compareByVal {
  bool operator()(const int leftKey, const int rightKey) const;
}

您无法访问比较功能中的值。没有(简单)的方法来按值对地图进行排序。


1
投票

简单地说,您不能。不确定使用的是哪个编译器,但是clang和gcc都给出有用的消息。与上下文。

clang:static_assert(__is_invocable<_Compare&, const _Key&, const _Key&>{},

gcc:if (__i == end() || key_comp()(__k, (*__i).first))

您可以看到clang和gcc都只用key而不是值来调用compare方法。这就是地图的工作方式。

如果要按值排序,则必须创建自己的自定义映射,或者更实际地,将值用作键。创建自己的地图来实现此目标比您想象的要困难得多,因为修改任何值后都必须对其进行排序。

© www.soinside.com 2019 - 2024. All rights reserved.