当前位置: 首页 > news >正文

C++,STL 048(24.10.25)

内容

set容器对内置数据类型、自定义数据类型指定排序规则。

运行代码

(1)内置数据类型

#include <iostream>
#include <set>using namespace std;// set容器默认排序规则为升序(从小到大),可以通过仿函数来改变排序顺序
// 仿函数就是在类中重载了()运算符,使这个类有了类似函数的行为
class myCompare
{
public:bool operator()(int v1, int v2) const // 注意加const{return v1 > v2; // 更改为降序(从大到小)}
};void test01()
{// set容器要在还没入插数据之前对排序进行改变set<int, myCompare> s1; // 注意变化s1.insert(20);s1.insert(30);s1.insert(40);s1.insert(10);// 注意迭代器的变化for (set<int, myCompare>::iterator it = s1.begin(); it != s1.end(); it++){cout << *it << " ";}cout << endl;
}int main()
{test01();return 0;
}

(2)自定义数据类型

#include <iostream>
#include <string>
#include <set>using namespace std;class Person
{
public:string m_Name;int m_Age;public:Person(string name, int age){this->m_Age = age;this->m_Name = name;}
};class comparePerson
{
public:bool operator()(const Person &p1, const Person &p2) const{return p1.m_Age > p2.m_Age;}
};void test01()
{// 对于自定义数据类型,set必须指定排序规则才可以插入数据set<Person, comparePerson> s1;Person p1("s1", 11);Person p2("s2", 22);Person p3("s3", 33);Person p4("s4", 44);s1.insert(p1);s1.insert(p2);s1.insert(p3);s1.insert(p4);for (set<Person, comparePerson>::iterator it = s1.begin(); it != s1.end(); it++){cout << it->m_Name << " " << it->m_Age << endl;}
}int main()
{test01();return 0;
}

输出结果


http://www.mrgr.cn/news/59351.html

相关文章:

  • javascript实现aes算法(支持微信小程序)
  • 第五章 nfs服务器
  • k8s和ipvs、lvs、ipvsadm,iptables,底层梳理,具体是如何实现的
  • 【ArcGIS Pro实操第5期】全局及局部空间插值:GPI、LPI、IDW等
  • 【Python爬虫实战】Selenium自动化网页操作入门指南
  • gin入门教程(3):创建第一个 HTTP 服务器
  • XCode16中c++头文件找不到解决办法
  • SQLI LABS | Less-12 POST-Error Based-Double quotes-String-with twist
  • 第二十六节 直方图均衡化
  • S-Function
  • Python | Leetcode Python题解之第514题自由之路
  • Leetcode刷题笔记13
  • 安全日志里提示:C:\Windows\System32\dasHost.exe
  • mysql5.7.44 arm 源码编译安装
  • Linux常用命令1
  • python源码编译—Cython隐藏源码(windows)
  • [dasctf]howtodecompile
  • xlnt加载excel报错:‘localSheetId‘ expected
  • 【Spring】控制反转 依赖注入(本文内容由大模型生成)
  • 安卓基础001
  • HarmonyOS NEXT初级案例:网络数据请求
  • uni-app应用级生命周期和页面级生命周期
  • 动态IP是什么?
  • Qt Creator中的项目栏
  • 说说SQL调优
  • 软考系统分析师知识点二四:错题集11-20