1、案例描述:
将student自定义数据类型进行排序,student中属性有姓名、年龄、身高,体重
2、排序规则:
按照年龄进行升序,如果年龄相同按照身高进行降序,如果年龄身高都相同按照体重进行降序
3、示例代码
#include<iostream>
#include<string>
#include<list>
using namespace std;
class student//要插入容器的数据类型
{
public:
student(string name,int age,int height,int weight)
{
this->m_name = name;
this->m_age = age;
this->m_height = height;
this->m_weight = weight;
}
string m_name;
int m_age;
int m_height;
int m_weight;
};
void printfList(const list<student> L)
{
for (list<student>::const_iterator it = L.begin();it != L.end();it++)
{
cout << it->m_name << " " << it->m_age << " " << it->m_height <<" "<< it->m_weight << endl;
}
cout << endl;
}
//自定义数据类型的排序,要指定排序规则(高级排序)
bool Compare(student& s1, student& s2)
{
if (s1.m_age == s2.m_age)//如果年龄相同,按照身高降序,否则按年龄升序
{
return s1.m_height > s2.m_height;//前边的数大于后边的数,降序
}
else
{
return s1.m_age < s2.m_age;//前边的数小于后边的数,升序
}
}
bool Compare1(student& s1, student& s2)//可以增加多个排序条件,无非就是多加几个判断
{
if ((s1.m_height == s2.m_height) && (s1.m_age == s2.m_age))//如果年龄身高都相同,按照体重进行降序
{
return s1.m_weight > s2.m_weight;
}
if (s1.m_age == s2.m_age)//如果年龄相同,按照身高降序,否则按年龄升序
{
return s1.m_height > s2.m_height;//前边的数大于后边的数,降序
}
else
{
return s1.m_age < s2.m_age;//前边的数小于后边的数,升序
}
}
int main()
{
list<student> L;
student s1("张三", 20, 168, 150);
student s2("李四", 19, 169, 120);
student s3("王五", 21, 175, 180);
student s4("赵六", 19, 169, 200);
student s5("钱七", 22, 175, 130);
student s6("王八", 22, 168, 140);
student s7("王九", 19, 169, 140);
L.push_back(s1);
L.push_back(s2);
L.push_back(s3);
L.push_back(s4);
L.push_back(s5);
L.push_back(s6);
L.push_back(s7);
printfList(L);//排序前
L.sort(Compare1);
printfList(L);//排序后
return 0;
}