C++中set的使用
时间: 2025-07-10 07:39:22 浏览: 6
### C++ 中 `set` 容器的使用方法
#### 基本概念
`set` 是一种关联容器,用于存储唯一的键值并自动保持有序状态。它基于平衡二叉树实现,默认按照升序排列元素。
#### 默认构造与基本操作
可以通过默认构造函数创建一个空的 `set` 容器,并通过成员函数完成插入、删除和查找等操作[^2]。
```cpp
#include <iostream>
#include <set>
using namespace std;
int main() {
// 创建一个空的 set 容器
set<int> mySet;
// 插入元素
mySet.insert(10);
mySet.insert(5);
mySet.insert(20);
// 遍历 set 并打印其内容
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 查找元素是否存在
if (mySet.find(5) != mySet.end()) {
cout << "Element 5 is found." << endl;
}
// 删除指定元素
mySet.erase(10);
// 打印删除后的集合
for (auto value : mySet) {
cout << value << " ";
}
cout << endl;
return 0;
}
```
上述代码展示了如何定义一个整数类型的 `set`,并通过 `insert()` 方法向其中添加数据。由于 `set` 自动排序特性,最终输出的结果会按从小到大顺序显示。
#### 自定义比较规则
如果希望改变默认的排序方式(如降序),可以自定义仿函数类作为模板参数传递给 `set` 的第二个类型参数。下面是一个例子展示如何让 `set` 按照数值从大到小的方式存储:
```cpp
#include <iostream>
#include <set>
using namespace std;
class DescendingOrder {
public:
bool operator()(const int& lhs, const int& rhs) const {
return lhs > rhs; // 改变条件使得较大的数排在前面
}
};
int main() {
// 使用自定义仿函数来控制排序逻辑
set<int, DescendingOrder> customSet;
customSet.insert(300);
customSet.insert(100);
customSet.insert(200);
// 输出定制化后的 set 结果
for (auto elem : customSet) {
cout << elem << " "; // 应该依次输出 300 200 100
}
cout << endl;
return 0;
}
```
此段程序利用了一个名为 `DescendingOrder` 的仿函数类重新定义了两个整型之间的大小关系判断准则[^1]。
#### 复杂数据结构的支持
除了简单的基础数据类型外,还可以将更复杂的对象放入 `set` 当中。此时需要确保这些对象能够被正确比较以便维持内部秩序不变。
假设我们有一个表示学生信息的数据结构如下所示,则可通过重载 `<` 运算符或者提供额外的比较机制将其加入至 `set` 中管理起来。
```cpp
struct Student {
string name;
int age;
// 提供小于运算符支持
bool operator<(const Student& other) const {
if (age == other.age)
return name < other.name;
return age < other.age;
}
};
int main(){
set<Student> students;
students.emplace("Alice", 22);
students.emplace("Bob", 24);
...
}
```
这里省略了一些细节部分比如具体初始化过程等内容。但是可以看到当我们将 `Student` 类型实例存放到 `set` 后面时,得益于之前所写的 `<` 函数重载版本的帮助,在不需要任何其他辅助措施的情况下即可顺利完成整个流程。
阅读全文
相关推荐












