C++ map容器降序编译报错:error: no matching function for call to object of type ‘const MyCompare‘

今天在学习C++的map容器排序时,跟着老师的课程做map容器的降序排序时编译报错,报错提示:

error: no matching function for call to object of type 'const MyCompare'

对着老师的代码看了半天,确认一个字符都没有敲错。但是视频中老师的可以正常输出,我这一摸一样的代码确报错。搞的很是恼火。。。

我的代码:

#include <iostream>
#include <string>
#include <map>
using namespace std;

//map容器排序

//排序用仿函数
class MyCompare
{
public:
    bool operator()(int v1, int v2)
    {
        return v1 > v2;
    }
};

//打印输出函数
void printMap(const map<int, string, MyCompare> &m)
{
    for (map<int, string, MyCompare>::const_iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "序号:" << (*it).first << "  姓名:" << it->second << endl;
    }
    cout << endl;
};


void test01()
{
    //创建map容器对象
    map<int, string, MyCompare> m1;

    //插入数据
    m1.insert(make_pair(5, "黄忠"));
    m1.insert(make_pair(3, "张飞"));
    m1.insert(make_pair(4, "赵云"));
    m1.insert(make_pair(6, "马超"));
    m1.insert(make_pair(1, "刘备"));
    m1.insert(make_pair(2, "关羽"));

    printMap(m1);
};

int main()
{
    test01();

    return 0;
};

错误截图:

 看提示,似乎说是MyCompare类少了const,好,加const:

class MyCompare
{
public:
    bool operator()(const int v1, const int v2)
    {
        return v1 > v2;
    }
};

继续编译还是报错。。。

最后查资料,啥的搞了一个多小时。最后在重载函数后面添加了const,再编译就好了:

class MyCompare
{
public:
    bool operator()(int v1, int v2) const
    {
        return v1 > v2;
    }
};

具体原因最后还是不知道为啥,期望看到本文的大神帮忙解答下。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值