zoukankan      html  css  js  c++  java
  • 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.1Toolsmingw492_32i686-w64-mingw32includec++itsstl_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之后运行成功。

  • 相关阅读:
    初学java-基础
    初学java-基础
    HYPER-V 实现管理器远程管理虚拟机
    zeromq rpc原型
    haproxy+keepalived
    [转]序列化悍将Protobuf-Net,入门动手实录
    RabbitMQ的几种应用场景
    redis数据类型及使用场景
    [转]DDD领域驱动设计基本理论知识总结
    Centos 下编译安装Redis
  • 原文地址:https://www.cnblogs.com/BASE64/p/14318380.html
Copyright © 2011-2022 走看看