在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
以下是代码: #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&)'
分析原因: 写了一个代替map容器默认排序的比较仿函数,提示说写的这个函数没有跟系统匹配的,对比发现,我写的仿函数参数没有用const修饰,对参数加上const之后运行成功。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论