黑馬程序員匠心之作|C++教程從0到1入門編程,學(xué)習(xí)編程不再難

P235_map容器_按自定義類型排序
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <map>
using namespace std;
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)const {
return p1.m_Age > p2.m_Age;
}
};
void test() {
map<Person, int,myCompare>m;
Person p1("娃達",7);
Person p2("速度",3);
Person p3("茍富",8);
Person p4("換個",4);
m.insert(make_pair(p1, 7));
m.insert(make_pair(p2, 3));
m.insert(make_pair(p3, 8));
m.insert(make_pair(p4, 4));
for (map<Person, int,myCompare>::iterator it = m.begin(); it != m.end(); it++) {
cout << "name = " << it->first.m_Name << " age = " << it->second << endl;
}
}
int main() {
test();
return 0;
}