栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 11 stl---->list链表 排序sort添加回调函数,这TM什么原理?

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 11 stl---->list链表 排序sort添加回调函数,这TM什么原理?

#include 
#include 
using namespace std;

class person
{
private:
    int age;
    string name;
public:
    person(int a = 0,string s = ""):age(a),name(s) {}
    int getAge() const {return age;}
    string getName() const {return name;}

public:
    bool operator==(const person& p) {return age == p.age && name == p.name ? true : false;}
    bool operator()(const person& p1,const person& p2) {return p1.age > p2.age ? true : false;}
};

bool Compare(const person& p1,const person& p2)
{
    return p1.getAge() < p2.getAge();
}

int main()
{
    list ilist;
    person p1(5,"a");
    ilist.push_back(p1);
    ilist.push_back(person(2,"b"));
    ilist.push_back(person(0,"c"));
    ilist.push_back(person(1,"d"));
    ilist.push_back(person(3,"e"));
    ilist.push_back(person(1,"f"));
    ilist.push_back(person(4,"g"));

    //ilist.sort(Compare);//回调函数,这么TM什么原理,内部咋个排序的?
    ilist.sort(person());//防函数版本,即构造匿名对象,调用运算符()重载:temp()(p1,p2)

    for(auto it = ilist.begin(); it != ilist.end(); it++)
    {
        cout << it->getAge() << " " << it->getName() << endl;
    }

    cout << "---------------------------------------" << endl;

    ilist.remove(person(1,"d"));//移除和person(1,"d")相等的元素,相等判断 依靠重载operator==

    for(auto it = ilist.begin(); it != ilist.end(); it++)
    {
        cout << it->getAge() << " " << it->getName() << endl;
    }
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018102.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号