一、自定义比较函数
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{
string name;
int age;
};
bool cmp(const Node a, const Node b)
{
return a.age < b.age; // < 就是前面的小于后面的,即从小到大排序
}
int main()
{
struct Node nodes[3];
nodes[0].name = "zhang";
nodes[0].age = 18;
nodes[1].name = "wang";
nodes[1].age = 20;
nodes[2].name = "li";
nodes[2].age = 19;
sort(nodes, nodes + 3, cmp);
for(int i = 0; i < 3; ++i) {
cout << nodes[i].age << endl;
}
}
二、结构体内嵌比较函数
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{
string name;
int age;
// 这里是cpp的运算符重载,重载了 <
bool operator < (const Node& a) const
{
return age < a.age; // < 就是从小到大排序
}
};
int main()
{
struct Node nodes[3];
nodes[0].name = "zhang";
nodes[0].age = 18;
nodes[1].name = "wang";
nodes[1].age = 20;
nodes[2].name = "li";
nodes[2].age = 19;
sort(nodes, nodes + 3);
for(int i = 0; i < 3; ++i) {
cout << nodes[i].age << endl;
}
}