C++出现error: no match for call to ‘(MyCompare) (const key_type&

以下是代码

#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

class Person{
public:
    string m_Name;
    int m_Age;
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
};
class MyCompare{
public:
    bool operator()(Person &p1, Person &p2)
    {
        return p1.m_Age > p2.m_Age;
    }
};
void printPerson( map<Person, int, MyCompare> &mp)
{
    for(map<Person, int, MyCompare>::iterator it = mp.begin(); it != mp.end(); it++)
    {
        cout << (*it).first.m_Name << " " << it->first.m_Age << endl;
     }
}
void test01(void)
{
    map<Person, int, MyCompare> mp;
    Person p1("aaa", 30);
    Person p2("bbb", 40);
    Person p3("ccc", 10);
    Person p4("ddd", 28);

    mp.insert(pair<Person, int>(p1, 1));
    mp.insert(pair<Person, int>(p2, 2));
    mp.insert(pair<Person, int>(p3, 3));
    mp.insert(pair<Person, int>(p4, 4));

    printPerson(mp);

}
int main(void)
{
    test01();
    system("pause");
    return 0;
}

运行报错

D:\Qt5.6.1\Tools\mingw492_32\i686-w64-mingw32\include\c++\bits\stl_tree.h:1445: error: no match for call to '(MyCompare) (const key_type&, const Person&)'

__comp = _M_impl._M_key_compare(__k, _S_key(__x));

^

分析原因

写了一个代替map容器默认排序的比较仿函数,提示说写的这个函数没有跟系统匹配的,对比发现,我写的仿函数参数没有用const修饰,对参数加上const之后运行成功。
原文链接: https://www.cnblogs.com/BASE64/p/14318380.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/207612

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午10:59
下一篇 2023年2月12日 下午11:00

相关推荐