C++之STL(5)之 set 与 multiset

本文详细介绍了C++标准库中的set与multiset容器的基本用法,包括数据的插入、查找、计数及删除等操作,并展示了如何利用这两个容器进行自动排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

set(集)  multiset(多集) 

两者都是为了保存大量数据的,但是不同的是 前者  保存的数据不重复,而后者 是允许 重复的。

其保存的数据非常快,尤其是大量数据的时候。


但其有一个缺点:就是数据插入的时候比顺序容器慢些(vector 、 list 、 deque)。

基本操作有:

inset;

count 和 find;

erase

注意:不能通过find进行修改了。

两者可以进行自动排序哦!

#include <iostream>
#include <set>

using namespace std;

template<typename Container>
void PrintContents(const Container & c);


int main()
{
	set<int> a;
	multiset<int> multiset_a;

	// a里面的数据不允许重复,但当你插入一个重复的数值的时候,它也不会报错,它会自动过滤  

	a.insert(3);
	a.insert(6);
	a.insert(1);
	a.insert(100);
	a.insert(100);

	cout << "显示set里面的数据:" << endl;	// set里面自动排序

	/*set<int>::const_iterator i = a.begin();
	
	while (i != a.end())
	{
		cout << *i << endl; 
		i++;
	}
	cout << endl;*/
	PrintContents(a);

	cout << a.count(300)<<endl;
	
	// multiset_a就可以保存重复的数据
	multiset_a.insert(a.begin(), a.end());	//	a里面的数据全部插入multiset_a中 
	multiset_a.insert(100);
	multiset_a.count(100);

	// count(50) 集合里存在50这个元素有多少个
	cout << "multiset_a里面有" << multiset_a.count(100) << "个3000" << endl;
	//
	cout << "显示multiset里面的数据:" << endl;	// set里面自动排序

	/*multiset<int>::const_iterator j = multiset_a.begin();

	while (j != multiset_a.end())
	{
		cout << *j << endl;
		j++;
	}
	cout << endl;*/

	PrintContents(multiset_a);
	//
	system("pause");
	return 0;
}

template<typename Container>
void PrintContents(const Container & c)
{
	Container::const_iterator i = c.begin();
	while (i != c.end())
	{
		cout << *i << endl;
		++i;
	}
	cout << endl;
}

#include<iostream>
#include<set>

using namespace std;
typedef set<int> SETINT;

int main()
{
	SETINT a;

	a.insert(5);
	a.insert(3);
	a.insert(1);
	a.insert(10);

	SETINT::const_iterator i;
	for (i = a.begin(); i != a.end(); i++)
	{
		cout << *i << endl;
	}

	SETINT::iterator i_found = a.find(3);		// find返回的结果是一个迭代器
	if (i_found != a.end())
	{
		cout << "找到了:" << *i_found << endl;
	}
	else
		cout << "没有找到:" << endl;
	// set 里面的数据不能直接修改,因为它默认会排序的。要想修改的话,先删除,之后重新添加
	//
	system("pause");
	return 0;
}


#include<iostream>
#include<set>

using namespace std;

typedef multiset<int> MSETINT;

int main()
{
	MSETINT a;

	a.insert(43);
	a.insert(78);
	a.insert(22);
	a.insert(-1);
	a.insert(124);
	a.insert(78);

	MSETINT::const_iterator i;

	cout << "multiset里面有" <<a.size() <<"个数据。"<< endl;
	cout << "每一个数据是:" << endl;
	for (i = a.cbegin(); i != a.end(); i++)
	{
		cout << *i << endl;
	}

	cout << "要删除的数据是:" << endl;
	int nNumberToErase = 0;
	cin >> nNumberToErase;

	a.erase(nNumberToErase);
	cout << "删除后:" << endl;
	cout << "multiset里面有" << a.size() << "个数据。" << endl;
	for (i = a.begin(); i != a.end(); i++)
	{
		cout << *i << endl;
	}
	a.clear();//清空
	//
	system("pause");
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值