#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Person
{
public:
string name;
int age;
int height;
Person(string name , int age , int height)
{
this->name = name;
this->age = age;
this->height = height;
}
friend ostream& operator << (ostream &os , Person &p);
};
ostream& operator << (ostream &os , Person &p)
{
cout<<"姓名:"<<p.name<<" 年龄:"<<p.age<<" 身高:"<<p.height<<endl;
return os;
}
bool comperson(Person &p1 , Person &p2)
{
//p1.xx < p2.xx 按xx从小到大顺序排序
//p1.xx > p2.xx 按xx从大到小顺序排序
if(p1.height == p2.height)
{
return p1.age > p2.age;
}
else
{
return p1.height < p2.height;
}
}
int main(void)
{
vector<int> v1 = {1 , 10 , 34 , 23 , 123 , 0 , 56};
sort(v1.begin() , v1.end()); //默认会从小到大排序
sort(v1.begin() , v1.end() , greater<int>()); //greater<指定数据类型>()是系统写好的比较器默认从大到小排序
for(auto V : v1)
{
cout<<V<<endl;
}
vector<Person> v2;
Person p1("GGBond" , 18 , 180);
Person p2("懒洋洋" , 8 , 150);
Person p3("熊大" , 23 , 210);
Person p4("熊二" , 20 , 210);
Person p5("灰太狼" , 36 , 170);
v2.push_back(p1);
v2.push_back(p2);
v2.push_back(p3);
v2.push_back(p4);
v2.push_back(p5);//将数据填充后,需要排序,按自定义顺序排序需要自定比较器
//按身高从小到大,如果身高一样,按照年龄降序
sort(v2.begin() , v2.end() , comperson);//自定义的比较器使用时不用写括号,直接写名字
for(auto x : v2)
{
cout<<x<<endl;
}
return 0;
}
C++模板编程-sort函数笔记
最新推荐文章于 2024-05-28 21:13:10 发布