set的用法

~ 2025-7-3 10:53:19

set

1、介绍

在C++中,set 是一个标准库中的容器,它存储的元素是唯一的,即不允许有重复的元素。set 内部元素默认按照升序排列,但也可以指定自定义的比较函数或比较对象来改变排序方式。set 通常使用在需要自动去重的场合。set 属于头文件 。

2、使用方法

2.1 头文件

首先,你需要包含 头文件来使用 set。

#include <set>

2.2 定义

你可以使用 set 来声明一个 set 容器。默认情况下,它使用 std::less 作为比较函数,其中 Key 是存储在 set 中的元素类型。即默认是从小到大排序的

set<int> mySet;

2.3 插入元素

使用 insert() 方法可以向 set 中插入元素。如果插入的元素已经存在于 set 中,则不会重复插入。

mySet.insert(10);
mySet.insert(20);
set<int>::iterator it = mySet.insert(10); // 不会插入,因为10已经存在
//set 里面的 insert(x) 函数其实是有返回值的,会返回一个这样的奇怪的东西:pair<set<int>::iterator,bool>

这个 pair 的第二项是一个 bool 类型的东西,代表插入是否成功。(意思就是只有集合里没有 x 的时候才能插入成功),第一项是一个迭代器,如果插入成功的话,它会返回 x 在集合里的位置,我们可以这样:

set<int> s;
set<int>::iterator p = s.insert(x).first;
bool success = s.insert(y).second;
if(success){
    cout << "y插入成功";
}

2.4 访问元素

由于 set 是有序集合,你可以使用迭代器来访问元素。

for (auto it = mySet.begin(); it != mySet.end(); ++it) {
    std::cout << *it << " ";
}

2.5 删除元素

使用 erase() 方法可以删除元素。你也可以通过迭代器删除元素。

mySet.erase(10); // 删除值为10的元素
// 或者使用迭代器删除
auto it = mySet.find(20); // 查找值为20的元素
if (it != mySet.end()) {
    mySet.erase(it); // 删除找到的元素
}

2.6 查找元素

使用 find() 方法可以查找元素。如果元素存在,返回指向该元素的迭代器;如果不存在,返回 end() 迭代器。

if (mySet.find(20) != mySet.end()) {
    std::cout << "Element found" << std::endl;
} else {
    std::cout << "Element not found" << std::endl;
}

2.7 自定义比较函数或对象

如果你想按照不同于默认升序的方式对元素进行排序,可以提供一个自定义的比较函数或对象。例如,使用自定义比较函数来按降序排列:

#include <functional> // 对于std::greater<T>
set<int, greater<int>> descendingSet; // 按降序排列的 set

2.8 set的二分函数

  • lower_bound(key_value) ,返回第一个大于等于key_value的定位器
  • upper_bound(key_value),返回最后一个大于等于key_value的定位器
#include <iostream>
#include <set>
 
using namespace std;
 
int main()
{
     set<int> s;
     s.insert(1);
     s.insert(3);
     s.insert(4);
     set<int>::iterator it;
     it = s.lower_bound(2);// 查找第一个大于等于2的位置
     cout<<*it<<endl; // 输出对应的数 3
     it = s.lower_bound(3);// 查找第一个大于等于3的位置, 
     cout<<*it<<endl;//输出对应的数 3
     it = s.upper_bound(3);// 查找第一个大于3的位置
     cout<<*it<<endl;//输出对应的数 4
     return 0;
}


我们会审查剪贴板内容,并对发布不合适内容的同学进行相应的处理