C++模板库STL——set

总结:
set去重且递增排序
代码:

#include <stdio.h>
#include <set>
using namespace std;

int main(){
	//set中的数据是自动递增排序,而且去重 
	set<int> st;
	st.insert(3);
	st.insert(5);
	st.insert(2);
	st.insert(3);
	//输出set中的数据 
	for(set<int>::iterator it = st.begin();it != st.end();it++){
		printf("%d ",*it);
	}
	printf("\n");
	//向set中填入数据 
	for(int i = 1;i <=15;i++){
		st.insert(i);
	}
	//输出数据 
	for(set<int>::iterator it = st.begin();it != st.end();it++){
		printf("%d ",*it);
	}
	printf("\n");
	//如果find后的数据不存在,则返回end的数据
	//find找到的是‘迭代器’ 
	set<int>::iterator it = st.find(6);
	printf("%d",*it);
	//删除数据(使用find找到迭代器来删) 
	st.erase(st.find(3));
	printf("\n"); 
	for(set<int>::iterator it = st.begin();it != st.end();it++){
		printf("%d ",*it);
	}
	//直接填入要删的数据值
	printf("\n");
	st.erase(2);
	for(set<int>::iterator it = st.begin();it != st.end();it++){
		printf("%d ",*it);
	}
	//删除区间的元素
	//这一句与上面冲突,似乎不能用? 
	//set<int>::iterator it = st.find(9);
	st.erase(it,st.end());
	printf("\n");
	for(set<int>::iterator it = st.begin();it != st.end();it++){
		printf("%d ",*it);
	}
	//获得元素的个数
	printf("\n");
	printf("%d\n",st.size()); 
	//清空set
	st.clear();
	printf("%d\n",st.size());  
	return 0;
}
发布了111 篇原创文章 · 获赞 3 · 访问量 2340

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104054454