8.list排序案例

2021-04-18  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<list>
#include<time.h>
//将Person自定义数据类型进行排序,Person中属性有姓名,年龄,身高
//排序规则:按照年龄进行排序,如果年龄相同按照身高进行降序排序

class Person
{
public:
    Person(string name,int age,int height)
    {
        this->m_Name = name;
        this->m_Age = age;
        this->m_Height = height;
    }
    string m_Name;
    int m_Age;
    int m_Height;
};

void PrintPerson(list<Person> l)
{
    for (list<Person>::iterator it = l.begin(); it != l.end(); it++)
    {
        cout << "姓名:" << it->m_Name << "\t"
            << "年龄:" << it->m_Age << "\t"
            << "身高:" << it->m_Height << endl;
    }
}
//指定排序规则
bool ComparePerson(Person& p1,Person& p2)
{
    if (p1.m_Age != p2.m_Age)
        return p1.m_Age < p2.m_Age;//按照年龄升序排序
    else
        return p1.m_Height > p2.m_Height;//年龄相同,按照身高升序排序

}
void test0801()
{
    list<Person> l;

    //准备数据
    for (int i = 0; i < 10; i++)
    {
        string nameSeed = "ABCDEFGHIJ";
        string name = "学生";
        name += nameSeed[i];

        int age = rand() % 81 + 20;

        int height = rand() % 31 + 160;

        Person p(name, age, height);

        l.push_back(p);
    }

    PrintPerson(l);

    //排序
    cout << "排序后:" << endl;
    l.sort(ComparePerson);
    PrintPerson(l);
}
int main()
{
    srand((unsigned int)time(NULL));

    test0801();

    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读