C++的set是基于红黑树实现的自动去重、升序排序关联容器,支持insert()返回值判重、自定义比较函数(如greater降序)、find/erase等O(log n)操作。
C++ 中的 set 是一个关联容器,自动去重且按升序排序(基于红黑树实现),无需手动排序或检查重复。它适合需要唯一、有序元素的场景,比如统计不重复关键词、维护有序ID列
表等。
包含头文件 ,定义 std::set,插入用 insert(),遍历可用范围 for 或迭代器。
示例:存储整数并自动去重排序
#include#include using namespace std; int main() { set s; s.insert(5); // 插入 5 s.insert(2); // 插入 2 s.insert(5); // 再插 5 → 无效果(已存在) s.insert(1); // 插入 1 for (int x : s) { cout << x << " "; // 输出:1 2 5 } }
set::insert() 返回一个 pair,其中 second 表示是否成功插入(true = 新元素,false = 已存在)。
find() 再 insert() 的冗余操作示例:
auto ret = s.insert(3);
if (ret.second) {
cout << "3 是新插入的";
} else {
cout << "3 已存在";
}
默认升序,可通过模板参数指定比较规则,实现降序或自定义逻辑。
greater
降序示例:
set> s_desc; s_desc.insert({3, 1, 4}); // 遍历输出:4 3 1
find()(返回迭代器,找不到为 end()),时间复杂度 O(log n)erase(key) 或 erase(iterator)
empty()、size()
lower_bound() / upper_bound() 快速定位边界基本上就这些。set 不复杂但容易忽略它的自动排序和不可重复特性——合理利用能省掉很多手写去重和 sort 的代码。