zoukankan      html  css  js  c++  java
  • c++STL容器之使用list容器对自己定义的数据类型进行排序

    需求;有一个类,类中有姓名和年龄成员变量,现在要按姓名升序排序,在姓名相同时按名字升序排序。

    #include<iostream>
    #include<list>
    #include<algorithm>
    using namespace std;
    //加入const限制只读,并使用const_iterator
    
    class Person {
    public:
        Person(string name, int age) {
            this->name = name;
            this->age = age;
        }
        string name;
        int age;
    };
    //重载左移运算符
    ostream& operator<<(ostream& cout, Person& p) {
        /*cout << "姓名:" << p.name << "," << "年龄:" << p.age;*/
        return cout;
    }
    void printPerson(const list<Person>& p) {
        for (list<Person>::const_iterator it = p.begin(); it != p.end(); it++) {
            cout <<"姓名:"<< (*it).name << "	"<<"年龄:" <<(*it).age<< endl;
        }
    }
    bool myCompare(Person &p1, Person &p2) {
        //若年龄相同
        if (p1.age == p2.age) {
            return p1.name < p2.name;
        }
        return p1.age <p2.age;
    }
    
    void test() {
        list<Person> lst;
        Person p1("tom", 12);
        Person p2("jack", 12);
        Person p3("sim", 16);
        Person p4("mike", 14);
        Person p5("bob", 11);
        Person p6("lol", 11);
        lst.push_back(p1);
        lst.push_back(p2);
        lst.push_back(p3);
        lst.push_back(p4);
        lst.push_back(p5);
        lst.push_back(p6);
        cout << "排序前:" << endl;
        printPerson(lst);
        lst.sort(myCompare);
        cout << "排序后:" << endl;
        printPerson(lst);
    }
    int main() {
        test();
        system("pause");
        return 0;
    }

    輸出:

     可以发现年龄已按升序排列,同时在年龄相同时,名字也是按首字母的顺序按升序排列。

  • 相关阅读:
    八数码难题 (codevs 1225)题解
    小木棍 (codevs 3498)题解
    sliding windows (poj 2823) 题解
    集合删数 (vijos 1545) 题解
    合并果子 (codevs 1063) 题解
    等价表达式 (codevs 1107)题解
    生理周期 (poj 1006) 题解
    区间 (vijos 1439) 题解
    区间覆盖问题 题解
    种树 (codevs 1653) 题解
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12112009.html
Copyright © 2011-2022 走看看