c++map 自定义排序

我在编写map用到的仿函数的时候,发现这样无法进行,我用的是vs2022,请问一下,为什么第一个无法运行,第二个可以,第一个错误提示为bool comparemap::operator ()(const std::pair<int,int> &,const std::pair<int,int> &) const”: 无法将参数 1 从“const _Kty”转换为“const std::pair<int,int> &”

img


第二张图可以运行为

img

没有正确地定义键类型。std::map的键类型默认情况下是std::less,其中Key是模板参数之一。你需要确保你的自定义键类型可以被std::less正确比较。

这个错误提示是因为您在定义 bool operator()(const std::pair<int,int>& a,const std::pair<int,int>& b) const; 时没有正确地声明模板参数类型 _Kty。

在使用仿函数作为map的比较器时,需要满足一定的模板参数要求。通常情况下,比较器的类型必须满足以下要求:

必须是一个类(class)或结构体(struct)
必须实现一个重载的函数调用运算符(operator()),该运算符的返回值类型必须是bool类型
operator()必须接受两个参数,并且参数类型必须与map中键类型相同或可转换为键类型。
根据您提供的信息,第一个代码无法通过编译,原因是在定义 bool comparemap::operator ()(const std::pair<int,int>&,const std::pair<int,int>&) const 时,没有正确地声明模板类型 _Kty,从而导致编译器无法识别第一个参数的类型。因此,您可以尝试将函数定义修改为:

template <typename _Kty>
bool comparemap::operator()(const _Kty& a, const _Kty& b) const {
    // your comparasion logic here
}

这里我们使用了模板类型 _Kty,并将其用于定义函数参数和返回类型,这样就可以确保参数类型与键类型相同或可转换为键类型了。

而第二段代码,因为使用了默认的比较器 std::less,所以不需要自定义 operator() 函数,可以直接使用。

希望能够帮助您解决问题。