FX-std::set
std::set
是 C++ 标准库中的一个关联容器,用于存储唯一元素,并按照特定顺序进行排序。它基于红黑树实现,因此插入、删除和查找操作的时间复杂度均为 O(log n)。以下是 std::set
的基本用法:
1. 包含头文件
#include <set>
2. 声明和初始化
std::set<int> mySet; // 声明一个存储 int 类型的 set
3. 插入元素
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
4. 删除元素
mySet.erase(20); // 删除值为 20 的元素
5. 查找元素
auto it = mySet.find(10);
if (it != mySet.end()) {
std::cout << "Element found: " << *it << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
6. 遍历元素
for (const auto& elem : mySet) {
std::cout << elem << std::endl;
}
7. 获取大小
std::cout << "Size of set: " << mySet.size() << std::endl;
8. 检查是否为空
if (mySet.empty()) {
std::cout << "Set is empty" << std::endl;
} else {
std::cout << "Set is not empty" << std::endl;
}
9. 清空 set
mySet.clear();
10. 自定义排序规则
struct MyCompare {
bool operator()(int a, int b) const {
return a > b; // 降序排序
}
};
std::set<int, MyCompare> myCustomSet;
myCustomSet.insert(10);
myCustomSet.insert(20);
myCustomSet.insert(30);
for (const auto& elem : myCustomSet) {
std::cout << elem << std::endl; // 输出: 30, 20, 10
}
11. 其他常用操作
-
lower_bound
: 返回第一个不小于给定值的元素的迭代器。 -
upper_bound
: 返回第一个大于给定值的元素的迭代器。 -
equal_range
: 返回一个包含所有等于给定值的元素的范围。
auto low = mySet.lower_bound(15);
auto high = mySet.upper_bound(25);
for (auto it = low; it != high; ++it) {
std::cout << *it << std::endl;
}
12. 注意事项
-
std::set
中的元素是唯一的,插入重复元素不会改变集合。 -
std::set
中的元素是有序的,默认是升序排列。
示例代码
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(20); // 重复元素,不会被插入
for (const auto& elem : mySet) {
std::cout << elem << " "; // 输出: 10 20 30
}
mySet.erase(20);
if (mySet.find(20) == mySet.end()) {
std::cout << "\n20 not found in set" << std::endl;
}
return 0;
}
std::set
是一个非常强大的容器,适用于需要快速查找和有序存储的场景。