众所周知,map容器在存储自定义数据类型时需重写排序规则对其进行排序,小弟虽重写了排序规则但是程序依然报错,代码如下;
#include<iostream>
using namespace std;
#include<map>
class Person
{
public:
Person(string name, int age)
{
this->m_Age = age;
this->m_Name = name;
}
int m_Age;
string m_Name;
};
class Compare
{
public:
bool operator()(const Person& p1,const Person& p2)
{
return p1.m_Age > p2.m_Age;
}
};
void test01()
{
map<Person, int,Compare> m;
Person p1("hhhh", 12);
Person p2("asd", 34);
Person p3("yyy", 11);
Person p4("q", 2);
m.insert(make_pair(p1, 2));
m.insert(make_pair(p2, 24));
m.insert(make_pair(p3, 29));
m.insert(make_pair(p4, 23));
for (map<Person, int, Compare>::iterator it = m.begin(); it != m.end(); it++)
{
cout << (it->first).m_Age << "--------" << it->second << endl;
}
}
int main() {
test01();