#include<iostream>
#include<list>
#include<algorithm>//标准算法头文件
#include<string>
using namespace std;
//list容器的排序案例
//按照年龄进行升序 如果年龄相同按照身高进行降序
class person {
public:
person(string name, int age, int hight) {
m_name = name;
m_age = age;
m_hight = hight;
}
string m_name;
int m_age;
int m_hight;
};
//指定排序规则
bool compareperson(person& v1, person& v2) {
if (v1.m_age == v2.m_age) {
return v1.m_hight > v2.m_hight;//如果年龄一样按照身高降序排序
}
else
{
return v1.m_age < v2.m_age;//年龄不一样按照年纪升序排列
}
}
void test() {
list<person>l;//默认构造
//准备数据
person p1("a", 15, 177);
person p2("b", 15, 178);
person p3("c", 16, 177);
//插入数据
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
for (list<person>::iterator it = l.begin(); it != l.end(); it++) {
cout << "姓名" << (*it).m_name ;
cout << "年龄" << it->m_age ;//迭代器可以当成指针来对待
cout << "身高" << (*it).m_hight << endl;
}
cout << "-------------------------" << endl;
cout << "排序后" << endl;
l.sort(compareperson);
for (list<person>::iterator it = l.begin(); it != l.end(); it++) {
cout << "姓名" << (*it).m_name;
cout << "年龄" << it->m_age;//迭代器可以当成指针来对待
cout << "身高" << (*it).m_hight << endl;
}
}
int main() {
test();
system("pause");
return 0;
}