STLset容器排序

STLset容器排序

学习目标:

set容器默认排序规则为从小到大,掌握如何改变排序规则

主要技术点:

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

代码示例一:

#include<iostream>
#include<set>
using namespace std;
//set容器排序
class Mycompare
{
   
public:
       bool operator()(int v1, int v2)
       {
   
              return v1 > v2;
       }
};
void test01()
{
   
       set<int>s1;
       s1.insert(10);
       s1.insert(40);
       s1.insert(50);
       s1.insert(30);
       s1.insert(20);
       for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
       {
   
              cout << *it << " ";
       }
     cout << endl;
       //指定排序规则为从小到大
       set<int, Mycompare>s2;
       s2.insert(10);
       s2.insert(40);
       s2.insert(50);
       s2.insert(30);
       s2.insert(20);
       for (set<int, Mycompare>::iterator it = s2.begin(); it != s2.end(); it++)
       {
   
              cout << *it << " ";
       }
       cout << endl;
}
int main()
{
   
       test01();
       system("pause");
       return 0;
}  

总结:利用仿函数可以指定set容器的排序规则

代码示例二:

#include<iostream>
#include <string>
#include<set>
using namespace std;
//set容器排序,存放自定义数据类型
class Person
{
   
public:
       Person(string name, int age)
       {
   
              this->m_Name = name;
              this->m_age = age;
       }
       string m_Name;
       int m_age;
};
class comPerson
{
   
public:
class comPerson
{
   
public:
       bool operator()(const Person&p1, const Person&p2)
       {
   
              //按照年龄 降序
              return p1.m_age > p2.m_age;
       }
};
void test01()
{
   
       //自定义数据类型,都会指定排序规则
       set<Person, comPerson>s;
       //创建对象
       Person p1("刘备", 24);
       Person p2("关羽", 34);
       Person p3("张飞", 44);
       Person p4("赵云", 54);
       s.insert(p1);
       s.insert(p2);
       s.insert(p3);
       s.insert(p4);
       for (set<Person>::iterator it = s.begin(); it != s.end(); it++)
       {
   
              cout << "姓名:" << it->m_Name
                     << " 年龄:" << it->m_age << endl;
       }
       
}
int main()
{
   
       test01();
       system("pause");
       return 0;
}

总结:
对于自定义数据类型,set必须指定排序规则才可以插入数据

数据结构与算法 文章被收录于专栏

本专栏收录数据结构与算法知识点

全部评论

相关推荐

看到这个内容真是闹麻了。。。。。。现在有了AI以后很多人面试都会作弊吗?&nbsp;那对老老实实面试的人岂不是不公平....
程序员牛肉:公平那是对小孩子讲的童话故事,成年人的世界只有能不能接受失败的后果。 你要是能接受面试作弊被发现之后多家公司联合永久拉黑的后果,你就搞。
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
Twilight_m...:表格简历有点难绷。说说个人看法: 1.个人基本情况里好多无意义信息,什么婚姻状况、健康状况、兴趣爱好、户口所在地、身份证号码、邮政编码,不知道的以为你填什么申请表呢。 2.校内实践个人认为对找工作几乎没帮助,建议换成和测开有关的项目,实在没得写留着也行。 3.工作经历完全看不出来是干什么的,起码看着和计算机没啥关系,建议加强描述,写点你在工作期间的实际产出、解决了什么问题。 4.个人简述大而空,看着像AI生成,感觉问题最大。“Python,C,C++成为我打造高效稳定服务的得力工具”、“我渴望凭借自身技术知识与创新能力,推动人工智能技术的应用发展,助力社会实现智能化转型”有种小学作文的美感。而且你确定你个人简述里写的你都会嘛?你AI这块写的什么“深入研究”,发几篇顶会的硕博生都不一定敢这么写。而且你AI这块的能力和软测也完全无关啊。个人简述建议写你对哪些技术栈、哪些语言、哪些生产工具的掌握,写的有条理些,而且最好是和测开强相关的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务