C++ implements sorting of custom data types

1. Scene description

      A Person class, with age and height attributes, is sorted in descending order of age; if the age is the same, sorted in descending order of height.

2. Code implementation

#include <iostream>
#include <list>
#include <string>

using namespace std;

class Person
{
public:
    Person(string name, int height, int age)
    {
        this->m_name = name;
        this->m_height = height;
        this->m_age = age;
    }

    string m_name;
    int m_height;
    int m_age;
};


void printList(list<Person>&L)
{
    for(list<Person>::iterator it=L.begin(); it != L.end(); it ++)
    {
        cout << "name:" << it->m_name << ", height:" << it->m_height << ", age:" << it->m_age << endl;
    }
}


class Compare
{
public:
    bool operator()(Person &p1, Person &p2)
    {
        if(p1.m_age == p2.m_age)
        {
            return p1.m_height > p1.m_height;
        }
        else
        {
            return p1.m_age > p2.m_age;
        }
    }
};


int main()
{
    list<Person>L;
    Person p1("guopei", 175, 30);
    Person p2("guofan", 170, 28);
    Person p3("guorong", 170, 32);
    Person p4("caige", 160, 28);
    Person p5("caipei", 170, 30);
    Person p6("huqiang", 170, 32);

    L.push_back(p1);
    L.push_back(p2);
    L.push_back(p3);
    L.push_back(p4);
    L.push_back(p5);
    L.push_back(p6);

    printList(L);

    cout << "-----------------------------" << endl;
    L.sort(Compare());
    printList(L);

    return 0;
}

 

Guess you like

Origin blog.csdn.net/Guo_Python/article/details/112361296