set
是 C++ 标准模板库(STL)中的关联容器,用于存储一组不重复的元素,并按照元素的键值进行排序。每个元素在 set
中都具有唯一的键值,并且元素按照键值的升序顺序进行排序。
特点:
-
唯一性:
set
中的元素是唯一的,相同的元素只能插入一次。 -
排序:
set
中的元素按照键值自动进行排序,默认是升序排序。 -
动态操作:可以动态地插入和删除元素,
set
会自动维护元素的有序性。 -
快速查找:由于
set
中的元素是按照键值排序的,因此可以在 O(log n) 的时间复杂度内进行快速查找操作。
- set的定义
set<typename> name;
typename可以是任何基本类型,如int、double、char、结构体等,也可以是STL标准容器,如vector、set、queue等。
set<int> name;
set<double> name;
set<char> name;
set<node> name; //node是结构体类型
- set容器内元素的访问
set只能通过迭代器访问:
set<typename>::iterator it;
例如下面的代码:
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(2);
st.insert(5);
st.insert(2);
st.insert(6);
st.insert(2);
for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
cout<<*it<<" ";
}
return 0;
}
输出结果:
2 5 6
从输出结果我们能发现,set内的元素自动递增排序,并且自动去除了重复元素。
- set常用函数
(1)insert()
insert(x)可以将x插入到set容器中,自动递增排序并去重,时间复杂度为O(logN),其中N为set内的元素个数,前面的例子即说明了这一点。
(2)find()
find(v)返回set中对应的v的迭代器,时间复杂度为O(logN),其中N为set内的元素个数。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
for(int i=0;i<5;i++){
st.insert(i+1);
}
set<int>::iterator it=st.find(1);
cout<<*it;
return 0;
}
输出结果:
1
(3)erase()
erase()可以删除单个元素,也可以删除一个区间内的所有元素。
① 删除单个元素
st.erase(it),it为所需要删除元素的迭代器。时间复杂度为O(1)。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(100);
st.insert(200);
st.insert(200);
st.insert(300);
st.erase(st.find(200)); //利用find()函数找到200,然后用erase删除它
for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
cout<<*it<<" ";
}
return 0;
}
输出结果:
100 300
st.erase(v),v为所需要删除元素的值。时间复杂度为O(logN),其中N为set内的元素个数。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(100);
st.insert(200);
st.insert(200);
st.insert(300);
st.erase(200); //删除set中值为200的元素
for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
cout<<*it<<" ";
}
return 0;
}
输出结果:
100 300
② 删除一个区间内的所有元素
st.erase(first, last)可以删除一个区间内的所有元素,其中first为所需要删除区间的起始迭代器,而last则为所需要删除区间的末尾迭代器的下一个地址,即删除[first,last)。时间复杂度为O(last-first)。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(100);
st.insert(200);
st.insert(300);
st.insert(400);
set<int>::iterator it=st.find(200);
st.erase(it,st.end()); //删除元素200至set末尾之间的元素
for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
cout<<*it<<" ";
}
return 0;
}
输出结果:
100
(4)size()
size()用来获得set内元素的个数,时间复杂度为O(1)。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(1);
st.insert(2);
st.insert(3);
st.insert(4);
cout<<st.size();
return 0;
}
输出结果:
4
(5)clear()
clear()用来清空set中的所有元素,时间复杂度O(N),其中N为set内的元素个数。
#include <iostream>
#include <set>
using namespace std;
set<int> st;
int main()
{
st.insert(1);
st.insert(2);
st.insert(3);
st.insert(4);
st.clear(); //清空set
cout<<st.size();
return 0;
}
输出结果:
0