set
翻译为 集合,是一个 内部自动有序 且 不含重复元素 的容器。
1. 定义
set<typaname> name;
// 示例
set<int> name;
set<double> name;
set<char> name;
set<node> name; // node 为结构体类型
// set 数组的定义
set<typename> Arrayname[arraySize]
// 数组定义示例
set<int> a[100];
2. 访问
set 只能用 迭代器 访问:
set<typename>::iterator it;
// 示例
set<int>::iterator it;
set<char>::iterator it;
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st;
st.insert(3);
st.insert(2);
st.insert(5);
st.insert(3);
// !! 不支持 it < st.end() 写法
for(set<int>::iterator it = st.begin(); it != st.end(); it++){
printf("%d", *it);
}
return 0;
}
3. 常用函数
(1)insert()
insert(x),将 x 插入 set 容器中,并自动递增排序和去重
(2)find()
find(value),返回 set 中对应值为 value 的迭代器
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st;
for(int i = 1; i <= 3; i++){
st.insert(i);
}
set<int>::iterator it = st.find(2);
printf("%d", *it);
return 0;
}
(3)erase()
① 删除 单个 元素:
- st.erase(it),it 为需要删除元素的迭代器
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st;
st.insert(100);
st.insert(200);
st.insert(100);
st.insert(300);
st.erase(st.find(100));
for(set<int>::iterator it = st.begin(); it != st.end(); it++){
printf("%d\n", *it);
}
return 0;
}
- st.erase(value),value 为所需要删除元素的值
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st;
st.insert(100);
st.insert(200);
st.erase(100);
for(set<int>::iterator it = st.begin(); it != st.end(); it++){
printf("%d", *it);
}
return 0;
}
② 删除一个区间内的所有元素: st.erase(first, last),即为删除 [first, last)
#include <stdio.h>
#include <set>
using namespace std;
int main(){
set<int> st;
st.insert(20);
st.insert(10);
st.insert(40);
st.insert(30);
set<int>::iterator it = st.find(30);
st.erase(it, st.end());
for(it = st.begin(); it != st.end(); it++){
printf("%d ", *it);
}
return 0;
}
(4)size()
st.size(); 获得 set 内元素的个数
(5)clear()
st.clear(); 清空 set 中的所有元素
3. 常见用途
set 最主要的作用是:自动去重 并 按升序排序。
延伸:若需处理不唯一的情况:multiset
unordered_set,以散列代替 set 内部的红黑树实现,使其可以用来处理只去重但不排序的需求。
——摘抄自《算法笔记》