在c++语言中,vector类型做排序主要使用sort()系统全局函数,默认只是针对内置数据(int,string)类型排序:
sort(vector.begin(), vector.end());
但如果是使用自定义类型,程序编译时就会报错,那么要怎么解决这一问题呢?
#include
using namespace std;
#include
#include
#include
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
bool myCompare(Person &v1, Person &v2) {
return v1.m_Age > v2.m_Age;
}
void test01() {
vector v;
Person p1("刘备", 24);
Person p2("关羽", 28);
Person p3("张飞", 25);
Person p4("赵云", 21);
Person p5("诸葛", 33);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
sort(v.begin(), v.end(), myCompare);
for (vector::iterator it = v.begin(); it != v.end(); it++) {
cout << "姓名:" << it->m_Name << ",年龄:" << it->m_Age << endl;
}
cout << endl;
}
int main() {
test01();
system("pause");
return 0;
}
姓名:诸葛,年龄:33
姓名:关羽,年龄:28
姓名:张飞,年龄:25
姓名:刘备,年龄:24
姓名:赵云,年龄:21
请按任意键继续. . .