zl程序教程

您现在的位置是:首页 >  前端

当前栏目

set容器和multiset容器的区别

set容器 区别
2023-09-14 09:02:34 时间

区别:

在这里插入图片描述

#include<iostream>
using namespace std;
#include<set>
void p(const set<int>& s)
{
	for (set<int>::const_iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	//无法使用[]和at方式访问
	//for (int i = 0; i < s.size(); i++)
	//{
	//	cout << s[i] <<" ";
	//	cout << s.at(i) << endl;
	//}
	cout << endl;
}
void m(const multiset<int>& m)
{
	for (multiset<int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test()
{
	set<int> s1;
	//set插入数据的时候会返回迭代器和一个bool类型表示插入是否成功
	//此时如果要同时接收两个返回值,需要用到pair对组
	pair<set<int>::iterator,bool> it=s1.insert(6);
	if (it.second)
	{
		cout << "插入元素成功!" << endl;
		cout << "插入元素为: " << *(it.first) << endl;
	 }
	else {
		cout << "插入元素失败" << endl;
	}
	//multiset容器与set区别在于前者可以插入重复元素
	multiset<int> m1 = { 5,3,7 };
	//multiset容器插入数据后只会返回一个迭代器,不会检测是否插入重复数据
	m1.insert(3);
	m(m1);

}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述