【C++学习纪录】set容器——使用仿函数改变排序

set容器默认是以升序方式对数据进行排序。若要改变它的排序方式,应在创建容器变量时使用仿函数。
一、简单地对数据进行降序排序

#include<iostream>
#include<set>
using namespace std;

//写仿函数,重载括号运算符,放在类中。
class temp
{
    public:
    //注意,是bool类型
    bool operator()(const int num1, const int num2)
    {
        return num1 > num2;
    }
};

int main()
{
    //在声明容器时将有函数的类名从第二个接口传入
    set<int, temp> s;
    s.insert(200);
    s.insert(500);
    s.insert(300);
    s.insert(700);
    s.insert(100);
    //打印容器
    for (set<int, temp>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << *it << ' ';
    }
    cout << endl;
    system("pause");
}

运行结果:

700 500 300 200 100
请按任意键继续. . .

二、对自定义类型进行降序排序

#include<iostream>
#include<set>
#include<string>
using namespace std;

class person
{
    public:
    person(string name, int height)
    {
        this->pheight = height;
        this->pname = name;
    }
    string pname;
    int pheight;
};

//写仿函数,重载括号运算符,放在类中。
class temp
{
    public:
    //注意,是bool类型, 且参数列表里要加const
    bool operator()(const person &p1, const person &p2)
    {
        return p1.pheight > p2.pheight;
    }
};

int main()
{
    //在声明容器时将有函数的类名从第二个接口传入
    person p1("Joe", 178);
    person p2("Sue", 168);
    person p3("Peter", 190);
    person p4("Frank", 185);
    set<person, temp> s;
    s.insert(p1);
    s.insert(p2);
    s.insert(p3);
    s.insert(p4);
    //打印容器中内容
    for (set<person, temp>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << (*it).pname << ' ' << (*it).pheight << endl;
    }
    system("pause");
}

运行结果:

Peter 190
Frank 185
Joe 178
Sue 168
请按任意键继续. . .

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值