STL 中的set和multiset 容器方法与API


前言

本章主要记录set和multiset 类中的各种方法,函数,以及它们的用途
本章内容仅为学习记录,如有纰漏,欢迎指正


1.简介:

  • 均属于关联式容器,底层是红黑树
  • 均默认为有序的(因为红黑树本质上是一个搜索二叉树,所以具有排序的特性)

2.构造和赋值

set<T> st;
set(const set &st);	//拷贝构造

set& operator= (const set &st); //赋值

3.大小和交换

size();
empty();
swap(st);

4.插入和删除

insert(ele);	//有返回值

clear();
erase(pos);		//根据迭代器删除
erase(beg, end);
erase(ele);

5.set和multiset区别

  1. set不允许重复元素(会查重),multiset允许重复元素(不会查重)
  2. set插入数据同时会返回插入结果
    返回pair(对组)类型,pair<iterator, bool>::<位置迭代器, 是否插入成功>
    接收返回值的类型例子(当然也可以用auto):
//例:
set<int>s;
pair<set<int>::iterator, bool> p = st.insert(10);
  1. multiset插入是直接返回iterator迭代器
//例:
multiset<int> ms;
multiset<int>::iterator it = ms.insert(10);

6.使用仿函数改变排序规则

  • set 的实例化有重载版本:set<int, 仿函数>
    传入的仿函数实际上是一个类,类可以作为参数传入set
    仿函数是()重载操作,可以模拟实现()的函数调用功能。
    测试:
#include<iostream>
using namespace std;
#include<set>
class MySort {
	public:
		bool operator()(const int& pre, const int& cur) const	//仿函数的实现
		{
			return pre > cur;
		}
	};
int main()
{
	set<int, MySort> st;
	st.insert(2);
	st.insert(1);
	st.insert(3);

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

	return 0;
}
  • 注:重载()运算符时,const的作用主要为告诉编译器不会改变传入的数据

unordered_set本质上是哈希实现,和以上的两个不一样

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KamikazePilot

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值