
- C++ set
- 前言
- 一、set 定义
- set 只能通过迭代器访问元素
- 二、set 常用函数
- 1、insert():插入元素(set 会自动排序、去重)
- 2、find():返回指定值的迭代器
- 3、clear():清空所有元素
- 4、erase():删除单个元素 或 删除区间元素
- 删除单个元素
- 删除区间元素
前言
在日常工作中,可能会遇到需要去掉重复元素的情况,而且有可能因这些元素的局限性而不能直接开散列表,这种情况下除了可以用数组解决,还可以使用 set 来保留元素本身而不考虑元素个数,并且 set 会让元素自动排序、去重,所以使用 set 能提升编程效率。
set 翻译为集合, 是一个 内部自动有序 且 不重复元素 的容器。
一、set 定义如果要使用 set 需要添加 set 头文件
#include
set<typename> name; //typename 可以是任何类型
//typename 为常规类型
set<int> Myint;
set<double> Mydouble;
set<node> Mynode; //node为结构体
//typename 为STL容器
set<vector<int> > Myset;
set<set<int> > Myset;
set 只能通过迭代器访问元素
set<typename>::iterator a;
//创建一个 set::iterator 类型的变量 a
//迭代器类似指针 可以用 *a 来访问元素
在C++ STL中 除开 string 和 vector 之外的STL容器都不支持 *(a + i) 的访问方式。(这里的 a 为上述迭代器)
二、set 常用函数 1、insert():插入元素(set 会自动排序、去重)时间复杂度 O(logN),其中 N 为元素个数
#include
#include
using namespace std;
set<int> Myset;
int main()
{
Myset.insert(5);
Myset.insert(4);
Myset.insert(1);
// begin()函数用来获取首地址
// end() 函数用来获取尾地址的下一个地址,不储存元素,作为迭代器末尾标志
// 不支持 a < Myset.end() 的写法,所以得 a != Myset.end()
for(set<int>::iterator a = Myset.begin(); a != Myset.end(); a ++)
{
cout << *a << endl;
}
return 0;
}
输出结果:
时间复杂度 O(logN),其中 N 为元素个数
#include
#include
using namespace std;
set<int> Myset;
int main()
{
for(int i = 0; i <= 5; i ++)
{
Myset.insert(i);
}
set<int>::iterator a;
a = Myset.find(3); //在set中查找 3 并返回迭代器
cout << *a << endl;
return 0;
}
输出结果:
3、clear():清空所有元素时间复杂度 O(N),其中 N 为元素个数
#include
#include
using namespace std;
set<int> Myset;
int main()
{
for(int i = 0; i <= 5; i ++)
{
Myset.insert(i);
}
//size()函数用于获取长度
cout << "clear()前长度为" << Myset.size() << endl;
Myset.clear();
cout << "Clear()后长度为" << Myset.size() << endl;
return 0;
}
输出结果:
时间复杂度 O(1)
#include
#include
using namespace std;
set<int> Myset;
int main()
{
for(int i = 0; i <= 5; i ++)
{
Myset.insert(i);
}
set<int>::iterator a = Myset.find(4); //拿到元素为 4 的迭代器 a
Myset.erase(a); //删除 4
for(set<int>:: iterator b = Myset.begin(); b != Myset.end(); b ++)
{
cout << *b << endl;
}
return 0;
}
输出结果:
时间复杂度为O(末尾迭代器 - 起始迭代器),删除区间为前闭后开
#include
#include
using namespace std;
set<int> Myset;
int main()
{
for(int i = 0; i <= 5; i ++)
{
Myset.insert(i);
}
set<int>::iterator a = Myset.find(2); //拿到元素为 2 的迭代器 a 作为删除区间的起始区间
set<int>::iterator b = Myset.find(4); //拿到元素为 4 的迭代器 b 作为删除区间的末尾区间
Myset.erase(a, b); //删除区间为[a, b),所以 4 不会被删除
for(set<int>::iterator c = Myset.size(); c != Myset.end(); c ++)
{
cout << *c << endl;
}
return 0;
}
输出结果:
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)