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

以下是代码

#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之后运行成功。

posted @ 2021-01-23 17:42  撑死算工伤吗  阅读(1537)  评论(1编辑  收藏  举报