set

Set知多少?

set,翻译为集合,是一个内部自动有序且不包含重复元素的容器,但是与vector不同,它其中的元素只能通过迭代器访问

C++中set是以红黑树作为底层实现的。

set最主要的作用是自动去重并按升序排序,因此碰到需要去重,但是却不方便直接开数组的情况,可以尝试用set解决。

此处引入一个链表查环的案例:

#include<iostream>
#include<set>
using namespace std;

struct Node{
	int val;
	Node *next = NULL;
};
Node *create(Node* head,int len) //环式链表 
{
	Node *L = new Node();
	Node *temp = new Node();
	L = head;
	for(int i = 0; i<len; i++)
	{

		int t;
		cout<<"pls input the data!"<<endl; 
		cin>>t;
		temp->val = t;
		
		L->next = temp;
		L = L->next;
		
	}	
	L->next = head;

	return head;
} 
int main()
{
	/* 检验链表中是否含有环
	set<Node*> tree;//存储的是指针的值也就是地址 
	
	Node *list = new Node();
	list->val = 0;
	create(list,5);
	Node *p = list;
	int count = 0; 
	while(p!=NULL)
	{
		tree.insert(p);
		count++;
		p=p->next;
		if(count!=tree.size())
		{
			cout<<"链表有环"<<endl;
			set<Node*>::iterator it = tree.begin();
			for(int i=0;it!=tree.end();i++,it++)
			{
				cout<<i<<":"<<*it<<endl;
			}
			break;
		}
	}
	*/
	/*批量插入 
	int arr[5] = {0,0,1,1,3};
	set<int> t;
	t.insert(arr,arr+5);
	set<int>::iterator ss = t.begin();
	for(int i=0;ss!=t.end();i++,ss++)
	{
		cout<<i<<":"<<*ss<<endl;
	}
	*/ 
	
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值