set,集合,内部自动有序且不含重复元素的容器。
头文件:#include < set > using namespace std;
set定义
单独定义一个set:
set<typename> name; //typename可以是任意基本类型,也可以是STL标准容器,vector/set/queue等
set<int> name;
set<char> name;
set<node> name; //node是结构体类型
//set数组定义
set<typename> Arrayname[arraySize];
set<int> a[100];
set容器内元素的访问
通过迭代器iterator访问:
set<int>::iterator it;
set<char>::iterator it;
可以通过*it来访问set里的元素,由于*除vector和string之外的STL容器都不支持 (it+i) 访问方式,因此只能枚举:
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st; //定义set容器
//插入一些数
st.insert(3);
st.insert(7);
st.insert(1);
st.insert(4);
st.insert(2);
st.insert(3);
st.insert(3);
st.insert(3);
//定义一个迭代器(指针)指向头部,set不支持it<st.end()写法
for(set<int>::iterator it=st.begin();it!=st.end();it++){
printf("%d",*it);
}
return 0;
}
输出12347,结果递增,且除去了重复元素3。
set常用函数实例
insert()
将x插入set容器中,自动递增排序和去重
find()
find(value)返回set中对应值为value的迭代器
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st; //定义set容器
for(int i=0;i<3;i++){
st.insert(i); //插入i
}
set<int>::iterator it=st.find(2); //在set中查找2,返回其迭代器
//以下两种写法等价
printf("%d\n",*it);
printf("%d\n",*(st.find(2)));
return 0;
}
erase()
- 删除单个元素
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st; //定义set容器
st.insert(100);
st.insert(400);
st.insert(200);
st.insert(100);
st.insert(100);
st.insert(600);
//利用find函数找到100,然后erase函数删除它
st.erase(st.find(100));
//直接删除值为200的元素
st.erase(200);
for(set<int>::iterator it=st.begin();it!=st.end();it++){
printf("%d ",*it);
}
return 0;
}
- 删除区间内的所有元素
set.erase(first,last),左闭右开
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st; //定义set容器
st.insert(100);
st.insert(400);
st.insert(200);
st.insert(800);
st.insert(300);
st.insert(600);
set<int>::iterator it; //定义迭代器
printf("----before:-----\n");
for(it=st.begin();it!=st.end();it++){
printf("%d ",*it);
}
printf("\n");
it=st.find(200);
st.erase(it,st.end()); //删除从200至末尾的元素
//不能写st.erase(it+1,it+4)或st.erase(200,400)
printf("-----after:------\n");
for(it=st.begin();it!=st.end();it++){
printf("%d ",*it);
}
return 0;
}
size()
获得set内元素的个数
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st; //定义set容器
st.insert(100);
st.insert(400);
st.insert(200);
st.insert(800);
st.insert(300);
st.insert(600);
set<int>::iterator it; //定义迭代器
printf("----before:-----\n");
for(it=st.begin();it!=st.end();it++){
printf("%d ",*it);
}
printf("\nset内元素个数:%d \n",st.size());
it=st.find(200);
st.erase(it,st.end()); //删除从200至末尾的元素
printf("-----after:------\n");
for(it=st.begin();it!=st.end();it++){
printf("%d ",*it);
}
printf("\nset内元素个数:%d \n",st.size());
return 0;
}
clear()
清空set中的所有元素
常见用途
set最主要作用是自动去重并按升序排序。
set中元素是唯一的,如果需要处理不唯一的情况,需要使用multiset。