set(集合),multiset容器及pair队组的创建

1.set的基本概念 :所有元素再插入时自动按升序排序,set/multiset属于关联式容器,底层结构是用二叉树实现的

set与multiset区别:

set中不允许容器中有重复的元素

multiset允许容器中有重复的元素

2.set的构造函数

3.set的大小和交换

4.set的插入和删除操作

5.set的查找和统计

cpp 复制代码
void test01()
{
	set<int> s;
	s.insert(10);
	s.insert(40);
	s.insert(20);
	s.insert(50);
	s.insert(20);
	s.insert(20);
	set<int>::iterator it=s.find(200);//find的返回值是迭代器,没找到返回s.end()
	if (it != s.end())
	{
		cout << "找到元素" << *it << endl;
	}
	else
	{
		cout << "没找到元素" << endl;
	}
	int num = s.count(20);//对于set而言没有重复元素,只返回0和1
	cout << num << endl;
}

6.set不能插入重复元素multiset能插入重复元素的原因

set插入数据的同时会返回插入结果,表示插入成功

multiset不会检测数据,因此可以插入重复数据

set.insert的底层代码:返回值是pair对组类型

multiset.insert的底层代码:返回值是迭代器

7.pair队组的创建

第一个元素first,第二个元素second

cpp 复制代码
void test01()
{
	pair<string, int> p1("张三", 16);
	cout << "姓名:" << p1.first << " 年龄:" << p1.second << endl;
	pair<string, int> p2 = make_pair("李四", 15);
	cout << "姓名:" << p2.first << " 年龄:" << p2.second << endl;
}

8.set容器的排序(利用仿函数可以改变排序规则)

set存放内置数据类型排序

cpp 复制代码
class mycompare
{
public://仿函数
	bool  operator()(int v1, int v2)const//这里要加const
	{
		return v1 > v2;//降序
	}
};
void test01()
{
	set<int> s1;
	s1.insert(20);
	s1.insert(50);
	s1.insert(30);
	s1.insert(10);
	s1.insert(40);
	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)//默认升序打印
	{
		cout << *it << " ";
	}
	cout << endl;
	set<int,mycompare> s2;//指定排序规则,两个参数都是数据类型//利用类里的仿函数可以指定排序规则
	s2.insert(20);
	s2.insert(50);
	s2.insert(30);
	s2.insert(10);
	s2.insert(40);
	for (set<int,mycompare>::iterator it = s2.begin(); it != s2.end(); it++)//降序打印
	{
		cout << *it << " ";
	}
}

set存放自定义数据类型排序

自定义类型都会指定排序规则

cpp 复制代码
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()(const Person &p1,const Person &p2)const//这里要加const
	{
		return p1.m_age>p2.m_age;//降序
	}
};
void test01()
{
	set<Person,mycompare> s1;
	Person p1("张三", 16);//如果年龄相同还要制定另一套规则
	Person p2("李四", 18);
	Person p3("王五", 15);
	Person p4("赵六", 14);
	s1.insert(p1);
	s1.insert(p2);
	s1.insert(p3);
	s1.insert(p4);
	for (set<Person,mycompare>::iterator it = s1.begin(); it != s1.end(); it++)//对于自定义数据类型,指定排序规则打印
	{
		cout << "姓名:" << it->m_name << " 年龄:" << it->m_age << endl;
	}
}
相关推荐
yiangL_1 天前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
JosieBook1 天前
【鸿蒙开源】把 Windows 任务栏上的流量表搬到鸿蒙 PC:TrafficMonitor 1.86 的 C++ 内核移植实践
c++·windows·harmonyos
Huangjin007_1 天前
【C++ 算法竞赛篇】STL 常用知识点速通指南
c++·算法
geovindu1 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk81631 天前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
敲上瘾1 天前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
炸膛坦客1 天前
单片机/C/C++八股:(三十三)取别名
c语言·c++·单片机
听情歌落俗1 天前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力1 天前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
ShineWinsu1 天前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog