加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++STL容器之使用list容器对自己定义的数据类型进行排序

发布时间:2020-12-16 09:06:48 所属栏目:百科 来源:网络整理
导读:需求;有一个类,类中有姓名和年龄成员变量,现在要按姓名升序排序,在姓名相同时按名字升序排序。 #includeiostream #include list #include algorithm using namespace std; // 加入const限制只读,并使用const_iterator class Person { public : Person(

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

#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;
     age;
};
重载左移运算符
ostream& operator<<(ostream& cout,Person& p) {
    /*cout << "姓名:" << p.name << "," << "年龄:" << p.age;*/
    return cout;
}
void printPerson(const list<Person>&for (list<Person>::const_iterator it = p.begin(); it != p.end(); it++) {
        cout <<"姓名:"<< (*it).name << t"<<年龄:" <<(*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);
    Person p3(sim16);
    Person p4(mike14);
    Person p5(bob11);
    Person p6(lol);
    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);
}
 main() {
    test();
    system(pause");
    return 0;
}

輸出:

?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读