7.set容器排序

2021-04-22  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<set>
#include<algorithm>
#include<time.h>

//set容器默认排序规则为从小到大,利用仿函数可以改变排序规则

class Person
{
public:
    Person(string name, int age)
    {
        this->m_Name = name;
        this->m_Age = age;
    }
    string m_Name;
    int m_Age;
};

class MyCompare
{
public:
    bool operator() (int v1,int v2)const//注意加const为常函数,若成员属性未加mutable关键字,则在常函数内不可以修改
    {
        return v1 > v2;
    }

};
//set存放内置数据类型
void test0701()
{
    set<int> s1;

    s1.insert(210);
    s1.insert(340);
    s1.insert(232);
    s1.insert(2342);
    s1.insert(234543);
    s1.insert(4363);

    for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
    {
        cout << (*it) << " ";
    }
    cout << endl;

    set<int,MyCompare> s2;

    s2.insert(210);
    s2.insert(340);
    s2.insert(232);
    s2.insert(2342);
    s2.insert(234543);
    s2.insert(4363);

    for (set<int, MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
    {
        cout << (*it) << " ";
    }
    cout << endl;
    
    
}
class ComparePerson
{
public:
    bool operator()(const Person p1,const Person p2)const
    {
        //按照年龄的降序排序

        return p1.m_Age > p2.m_Age;
    }
};
//set存放自定义数据类型(自定义数据类型都会指定排序规则)
void test0702()
{
    set<Person,ComparePerson> s;
    for (int i = 0; i < 10; i++)
    {
        string nameSeed = "ABCDEFGHIJ";
        string name = "学生";
        name += nameSeed[i];

        int age = rand() % 21 + 20;

        Person p(name, age);

        s.insert(p);
    }

    for (set<Person,ComparePerson>::iterator it = s.begin(); it != s.end(); it++)
    {
        cout << "姓名:" << it->m_Name << "\t"
            << "年龄:" << it->m_Age << endl;
    }
}

int main()
{
    srand((unsigned int)time(NULL));

    test0701();

    test0702();

    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读