C++ STL---set总结

  • 自动排序
  • 没有下标访问的方式
  • 查找的返回值两个:first是地址--可以用it指向,second是bool是否成功
  • set和map的iterator除非删除这个迭代器指向的,否则迭代器不会失效,因为是指针指向的。
  • set的插入和搜索速度为log2 N
#include <iostream>
#include <set>
using namespace std;

struct lesscomp{
	bool operator()(const int& a,const int& b)const
	{return a>b;}
};

int main()
{
/*创建,初始化,遍历*/
	/*创建,初始化1*/
	set<int> s1;//创建空的
	/*创建,初始化2*/
	int arr[]={1,2,8,4,5};
	set<int> s2(arr,arr+5);//数组初始化,自带排序
/*遍历方式*/
	set<int>::iterator it=s2.begin();
	for (;it!=s2.end();it++)
		cout<<*it<<" "; cout<<endl;
	/*创建,初始化3*/
	set<int,lesscomp> s3(arr,arr+5);//数组初始化,自定义排序
	set<int,lesscomp>::iterator it1=s3.begin();
	for(it1=s3.begin();it1!=s3.end();it1++)
		cout<<*it1<<" ";  cout<<endl;
	/*创建,初始化4*/
	set<int> s4(s2);

/*增加---插入*/
	/*插入1*/
	pair<set<int,lesscomp>::iterator,bool> p;
	p=s3.insert(7);
	if(p.second) cout<<"insert ok"<<endl;
	else cout<<"insert 7 fail"<<endl;
	/*插入2*/
	if(s3.insert(7).second) cout<<"insert ok"<<endl;
	else cout<<"duplicate insert 7fail"<<endl;
	it1 = s3.insert(10).first;//返回值的first是地址,second是bool是否成功
	cout<<*it1<<endl;
	/*插入3*/
	s3.insert(it1,7);
	cout<<*it1<<endl;//仍然指向10,说明这个10是你想插入的哪个红黑树中的重复节点
	for(it1=s3.begin();it1!=s3.end();it1++)//10 8 7 5 4 2 1
		cout<<*it1<<" ";  cout<<endl;

/*查找*/
	it1=s3.find(100);
	if(it1!=s3.end()) cout<<"find ok"<<endl;
	else cout<<"find fail"<<endl;
	set<int,lesscomp>::iterator itlow=s3.lower_bound (6);
	cout<<*itlow<<endl;
	set<int,lesscomp>::iterator itup=s3.upper_bound (6);
	cout<<*itup<<endl;			//10 8 7 5 4 2 1  逆序的lower_bound,upper_bound也逆序
	itlow=s3.lower_bound (7);   //     *       
	cout<<*itlow<<endl;
	itup=s3.upper_bound (7);	//       *
	cout<<*itup<<endl;
	set<int> s5;
	for(it1=s3.begin();it1!=s3.end();it1++)//10 8 7 5 4 2 1
		s5.insert(*it1);
	for(it=s5.begin();it!=s5.end();it++)//1  2 4 5 7 8 10
		cout<<*it<<" ";  cout<<endl;
	set<int>::iterator itlow1=s5.lower_bound (6);
	cout<<*itlow1<<endl;
	set<int>::iterator itup1=s5.upper_bound (6);
	cout<<*itup1<<endl;			
									//1 2 4 5 7 8 10顺序的lower_bound,upper_bound也顺序
	itlow1=s5.lower_bound (7);		//        *
	cout<<*itlow1<<endl;
	itup1=s5.upper_bound (7);		//          *
	cout<<*itup1<<endl;
								
/*删除*/
	it1=s3.find(7);
	//s3.erase(7);//会报错,因为这里it1已经失效。
	/*set和map的iterator除非删除这个迭代器指向的,否则迭代器不会失效*/
	s3.erase(it1,s3.end());
	for(it1=s3.begin();it1!=s3.end();it1++)
		cout<<*it1<<" ";  cout<<endl;
	return 0;
}
  •  

猜你喜欢

转载自blog.csdn.net/m0_37561165/article/details/81223139
今日推荐