set/multiset

 

set和multiset的特性是可以根据元素的值自动排序   ( 默认由小到大 ),set是以红黑树为底层机制,他的查找效率很好 ,set不允许重复元素出现, multiset允许重复元素出现;

set只允许insert()操作,不支持,sort(),top()之类的 

但是支持swap(),size(),empty()

        

 

    

#include<iostream>
#include<set>

using namespace std;

//set容器的初始化
void text01()
{
	set<int>s1;//默认排序,由小到大
	s1.insert(7);
	s1.insert(6);
	s1.insert(45);
	s1.insert(63);
	s1.insert(98);
	s1.insert(100);

	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
		cout << *it << ' ';
	cout << endl;



	//如何改变默认的排序方式

	//赋值操作
	set<int>s2;
	s2 = s1;

	//删除操作
	s1.erase(s1.begin());//按照元素删除,只是删除头节点
	s1.erase(7);//按照元素删除,删除set中的所有的元素 7
	cout << "删除头节点和删除所有的元素7后的set中的数据:::" << endl;
	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
		cout << *it << ' ';
	cout << endl;

	return;
}

//查找
void text02()
{
	//set只有实值
	set<int>s1;
	s1.insert(7);
	s1.insert(6);
	s1.insert(45);
	s1.insert(63);
	s1.insert(98);
	s1.insert(100);

	//find(key)如果key存在就返回改键元素的迭代器,否则返回end()
	set<int>::iterator ret = s1.find(45);
	if (ret == s1.end())
		cout << "没有找到!!" << endl;
	else cout << "find it" << endl;

	//lower_bound(keyElem):::返回第一个key>=keyElem元素的迭代器
	ret = s1.lower_bound(45);
	if (ret == s1.end())
		cout << "no" << endl;
	else cout << "ret:::" << *ret << endl;


	//upper_bound(keyElem):::返回第一个keykeyElem元素的迭代器
	ret = s1.upper_bound(45);
	if (ret == s1.end())
		cout << "no" << endl;
	else cout << "ret:::" << *ret << endl;
	

	//返回容器中key与keyelem相等的上下限的两个迭代器
	pair<set<int>::iterator, set<int>::iterator> myret = s1.equal_range(6);

	if (myret.first == s1.end())
		cout << "no :::" << endl;
	else cout << "myret.first:::" <<*myret.first << endl;

	if (myret.second == s1.end())
		cout << "no :::" << endl;
	else cout << "myret.first:::" << *myret.second << endl;



}
int main()
{
	//text01();
	text02();
	return 0;
}

更改set 的默认排序方式

  

#include<iostream>
#include<set>

using namespace std;

//更改set的默认排序方式

//仿函数
class cmp
{
public:
	bool operator()(int v1, int v2) const 
	{
		return v1 > v2;
	}
};
void text01()
{
	set<int,cmp>s1;//由大到小
	s1.insert(7);
	s1.insert(6);
	s1.insert(45);
	s1.insert(63);
	s1.insert(98);
	s1.insert(100);

	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
		cout << *it << ' ';
	cout << endl;

	return;
}

int main()
{
	text01();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值