1. 核心特性
• 唯一性:元素自动去重,不允许重复值。
• 有序性:元素默认按升序排列(可通过自定义比较器改变顺序)。
• 不可修改:元素值不可直接修改(可能破坏排序),需先删除再插入新值。
• 关联容器:通过键(即元素本身)访问,支持高效查询(对数时间复杂度)。
2. 底层实现
通常基于红黑树(平衡二叉搜索树)实现,保证插入、删除、查找的时间复杂度均为 O(log n)。
3. 基本操作示例
#include <iostream>
#include <set>
using namespace std;
int main() {
// 声明set
set<int> mySet;
// 插入元素
mySet.insert(3);
mySet.insert(1);
mySet.insert(4);
mySet.insert(1); // 重复元素不会被插入
// 遍历输出(自动排序)
for (int num : mySet) {
cout << num << " "; // 输出:1 3 4
}
cout << endl;
// 查找元素
auto it = mySet.find(3);
if (it != mySet.end()) {
cout << "Found: " << *it << endl;
}
// 删除元素
mySet.erase(3); // 删除值为3的元素
// 其他常用操作
cout << "Size: " << mySet.size() << endl; // 元素个数
cout << "Empty: " << mySet.empty() << endl; // 是否为空
mySet.clear(); // 清空set
return 0;
}
4. 自定义排序规则
set 的完整模板声明是:
template <class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
class set;
其中:
• 第一个参数 Key:元素的类型(这里是 int)
• 第二个参数 Compare:比较函数的类型(这里是 DescendingCompare)
#include <iostream>
#include <set>
using namespace std;
// 自定义降序比较器
struct DescendingCompare {
bool operator()(int a, int b) const {
return a > b; // 降序:a > b 时 a 排在前面
}
};
int main() {
set<int, DescendingCompare> descSet;
descSet.insert({5, 2, 8, 1, 9});
for (int num : descSet) {
cout << num << " "; // 输出:9 8 5 2 1
}
cout << endl;
return 0;
}
5. 常用成员函数
insert(value) 插入元素
erase(value) 删除指定元素
find(value) 查找元素,返回迭代器
count(value) 返回元素个数(0或1)
lower_bound() 返回第一个不小于值的迭代器
upper_bound() 返回第一个大于值的迭代器
begin()/end() 返回首尾迭代器
6. 相关容器
• multiset:允许重复元素的有序集合。
• unordered_set:基于哈希表的无序集合(查询更快,但无序)。
7. 注意事项
• 插入/删除操作不会使迭代器失效(被删除元素的迭代器除外)。
• 元素类型需支持比较(或提供自定义比较器)。
• 相比 vector/array,set 更适用于需要频繁查找和去重的场景。
898

被折叠的 条评论
为什么被折叠?



