C++ STL map容器的自定义类型的自定义排序
以下附代码
#include <iostream>
using namespace std;
#include <map>
#include <string>
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class MyCompare
{
public:
bool operator()(const Person &p1, const Person p2)
{
return p1.m_Age > p2.m_Age;
}
};
void test01()
{
map<Person, int, MyCompare> m;
Person p1("刘备", 24);
Person p2("关羽", 27);
Person p3("张飞", 25);
Person p4("赵云", 21);
m.insert(make_pair(p1, p1.m_Age));
m.insert(make_pair(p2, p2.m_Age));
m.insert(make_pair(p3, p3.m_Age));
m.insert(make_pair(p4, p4.m_Age));
for (map<Person, int, MyCompare>::const_iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << (*it).first.m_Name << " value = " << it->second << endl;
}
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}