c++ STL容器(2)set容器

set翻译为集合,是一个内部自动有序且不含重复元素的容器
set的定义

set<typename> name;

set<int> vi;
set<double> vi;
set<char> vi;
set<node> vi;//node可以是结构体

set<int> a[100]; //数组里面每个元素都是一个set集合

insert(x) 将x插入set容器中,并自动递增排序和去重

	//insert(x) 将x插入set容器中,并自动递增排序和去重
	st.insert(4);
	st.insert(3);
	st.insert(1);
	st.insert(2);
	//不支持<it.end()的写法
	for(set<int>::iterator it=st.begin();it!=st.end();it++){
    
    
		cout<<*it<<" ";//1 2 3 4
	}

set集合的遍历
set只能通过迭代器遍历
除了vector和string之外的stl容器都不支持*(it+i)的访问方式

//不支持<it.end()的写法
	for(set<int>::iterator it=st.begin();it!=st.end();it++){
    
    
		cout<<*it<<" ";//1 2 3 4
	}

set内的元素会自动递增排序,且自动去除了重复元素

find(value)返回set中对应值为value的迭代器

set<int>::iterator it=st.find(3); //查找值为3的元素返回其迭代器 
	cout<<*it<<endl; //如果查找的元素不存在会返回最后一个元素的迭代器 

erase()删除元素


//erase() 有两种用法一种是删除单个元素另一种是删除一个区间的所有元素
	//删除单个的方法又有两种
	//1.st.erase(it) it为所删元素的迭代器 可以和find连用 
	 //1 2 3 4
	st.erase(st.find(3)); 
	for(set<int>::iterator it=st.begin();it!=st.end();it++){
    
    
		cout<<*it<<" ";//1 2 4
	}
	cout<<endl;
	//2.st.erase(value) value为所删除元素的值 
	//1 2 4
	st.erase(1);
	for(set<int>::iterator it=st.begin();it!=st.end();it++){
    
    
		cout<<*it<<" ";//2 4
	}
	cout<<endl;
	st.insert(4);
	st.insert(3);
	st.insert(1);
	st.insert(2);
	//删除整个区间 
	//1 2 3 4
	st.erase(st.find(2),st.end());
	
	for(set<int>::iterator it=st.begin();it!=st.end();it++){
    
    
		cout<<*it<<" ";//1
	}

size()返回set内的元素个数

  //1 2 3 4
    cout<<st.size(); //4

clear()清空st中的所有元素

	st.clear(); 
	cout<<st.size();

empty() 判断是否为空

	st.clear(); 
	cout<<st.empty()<<endl;//1 true

lower_bound(k)
upper_bound(k)

	st.insert(4);
	st.insert(3);
	st.insert(1);
	st.insert(2);
	//1 2 3 4
	//lower_bound(k) 返回一个迭代器,指向键值不小于k的第一个元素 
	set<int>::iterator it=st.lower_bound(2);//寻找第一个大于等于2的数 
	cout<<*it<<endl;//2
	//upper_bound(k) 返回一个迭代器,指向键值大于k的第一个元素 
	 it=st.upper_bound(2); 
	 cout<<*it<<endl;//3

猜你喜欢

转载自blog.csdn.net/qq_44866153/article/details/108976290