• pair、set的排序规则(20221124)


    一、pair对组

    成对出现的数据,利用对组可以返回两个数据

    1、创建方式

    1) pairp(value1,value2);

    2)  pairp = make_pair(value1,value2);

    1. void test01()
    2. {
    3.     pairint>p("张三", 18);
    4.     cout << "姓名:" << p.first << " 年龄:" << p.second << endl;
    5.     pairint>p1 = make_pair("张三", 18);
    6.     cout << "姓名:" << p1.first << " 年龄:" << p1.second << endl;
    7. }

    二、set容器的排序

    默认从小到大,掌握如何改变其排序规则

    利用仿函数,改变其排序规则

    1. void printSet(set<int>&s)
    2. {
    3.     for (set<int>::iterator it = s.begin(); it != s.end(); it++)\
    4.     {
    5.         cout << *it << " ";
    6.     }
    7.     cout << endl;
    8. }
    9. //仿函数
    10. class Compare {
    11. public:
    12.     bool operator()(int v1, int v2) //重载()
    13.     {
    14.         return v1 > v2;
    15.     }
    16. };
    17. void test02()
    18. {
    19.     set<int>s1;
    20.     s1.insert(10);
    21.     s1.insert(20);
    22.     s1.insert(5);
    23.     s1.insert(20);
    24.     printSet(s1);//5 10 20 自动排序 且去除重复元素
    25.     //指定排序规则 从大到小
    26.     set<int,Compare>s2;
    27.     s2.insert(10);
    28.     s2.insert(20);
    29.     s2.insert(5);
    30.     s2.insert(20);
    31.     //单独写一个迭代器遍历
    32.     for (set<int, Compare>::iterator it = s2.begin(); it != s2.end(); it++)
    33.     {
    34.         cout << *it << " ";
    35.     }
    36.     cout << endl;
    37. }

    当存放自定义数据类型时:

    1. class Person {
    2. public:
    3.     int m_age;
    4.     string m_name;
    5.     Person(string name, int age)
    6.     {
    7.         this->m_name = name;
    8.         this->m_age = age;
    9.     }
    10. };
    11. class PCompare {
    12. public:
    13.     bool operator()(const Person &p1,const Person &p2)
    14.     {
    15.         return p1.m_age > p2.m_age;
    16.     }
    17. };
    18. void printCPerson(set&s)
    19. {
    20.     for (set::iterator it = s.begin(); it != s.end(); it++)
    21.     {
    22.         cout << "姓名:" << it->m_name << " 年龄:" << it->m_age << endl;
    23.     }
    24.     cout << endl;
    25. }
    26. void test03()
    27. {
    28.     //对于自定义的数据类型 必须指定排序规则
    29.     sets2;
    30.     Person p1("张三", 19);
    31.     Person p2("李四", 18);
    32.     Person p3("赵云", 29);
    33.     Person p4("张飞", 30);
    34.     Person p5("刘备", 39);
    35.     s2.insert(p1);
    36.     s2.insert(p2);
    37.     s2.insert(p3);
    38.     s2.insert(p4);
    39.     s2.insert(p5);
    40.     printCPerson(s2); //注意 PCompare类一定要在调用前先定义 不然会报错
    41. }

  • 相关阅读:
    开源AI智能名片小程序在私域流量运营中的“及时法则”深度应用与策略探讨
    将你的桌面变成一个雨滴窗口:关于两个有趣的应用的整合
    vue自定义指令
    Guitar Pro 8win10最新版吉他学习 / 打谱 / 创作
    贝加莱MQTT功能
    网络专线学习
    R语言ggplot2可视化:使用ggcharts包的pyramid_chart函数可视化人口金字塔图(pyramid chart)
    maven聚合和继承
    javaweb
    【服务器数据恢复】infortrend存储RAID6数据恢复案例
  • 原文地址:https://blog.csdn.net/qq_60143666/article/details/128027661