#include<iostream>
#include<set>
using namespace std;
/*
set为集合,是一个内部自动有序且不含重复元素的容器。
当出现需要去掉重复元素的情况,而且有可能因这些元素比较大或者类型不是 int 型而不能直接开散列表,
在这种情况下就可以用 set 来保留元素本身而不考虑它的个数。
当然,上面说的情况也可以通过再开一个数组进行下标和元素的对应来解决,但是 set 提供了更为直观的接口
,并且加入 set 之后可以实现自动排序。
set 最主要的作用是自动去重并按升序排序,因此碰到需要去重但是却不方便直接开数组的情况,可以用 set 解决。
set 中元素是唯一的,如果需要处理不唯一的情况,则需要使用 multiset。
unordered_set 可以用来处理只去重但不排序的需求,速度比 set 要快得多。
*/
//set定义
multiset<int>mst1;
#include<unordered_set>
unordered_set<int>ust1;
set<int> st1;
set<double> st2;
set<char> st3;
//set<node> st4; //node是结构体的类型
//set<vector<int> > st5; //如果typename 是一个STL容器,那么定义时要记得在 >>之间要加空格
//定义 set 数组:
//set<typename> Arrayname[arraySize];
//这样 Arrayname[0] ~ Arrayname[arraySize -1] 中每一个都是一个 set 容器。
void setFind(){
auto it = st1.find(40);//可以找到
if (it != st1.end()) {//找到后输出40
cout << "Found " << *it << endl;
} else {
cout << "Not found" << endl;
}
auto it2 = st1.find(3);//找不到的情况
if (it2 != st1.end()) {
cout << "Found " << *it2 << endl;
} else {
cout << "Not found" << endl;
}
/*find详细介绍
find(value) 返回 set 中对应值为 value 的迭代器,时间复杂度为 O(logN),其中 N 为 set 内的元素个数。
在 C++ 中,set 容器提供了多种方式查找元素,包括 find()、lower_bound()、upper_bound() 和 equal_range()。
find() 函数可以在 set 容器中查找指定元素,如果找到就返回指向该元素的迭代器,否则返回 set::end()
*/
}
void setDelete(){
//method1:直接删除元素
set<int> myset = {10, 20, 30, 40, 50, 60};
myset.erase(30); // 删除元素 30
//method2:删除一定区间内的元素
auto it = myset.find(40);
myset.erase(it, myset.end()); // 删除元素 40 及其后面的所有元素
for (auto x : myset) {
cout << x << " ";
}
cout << endl;
}
void setClear(){
//method1:使用swap
set<int> myset1 = {10, 20, 30, 40, 50, 60};
set<int> myset2;
myset1.swap(myset2);//两个集合交换,一个是空集合,交换后相当于清空
// set<int>().swap(myset1);//直接清空元素
cout << "Size of myset1: " << myset1.size() << endl; // 输出 0
cout << "Size of myset2: " << myset2.size() << endl; // 输出 6
//method2使用clear
set<int> myset = {10, 20, 30, 40, 50, 60};
myset.clear(); // 清空容器中的所有元素
cout << "Size of myset: " << myset.size() << endl; // 输出 0
}
int main(){
//insert(x) 可将 x 插入 set 容器中,并自动递增排序和去重,时间复杂度为 O(logN),其中 N 为 set 内的元素个数。
for(int i=0;i<5;i++){
st1.insert(i*20);
}
setFind();
setDelete();
setClear();
}
C++STL容器set的基本操作
最新推荐文章于 2025-03-29 16:14:18 发布