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;
}