#P1581. set的用法

set的用法

Description

在 C++ 中,`std::set` 是标准模板库(STL)中的一个**关联容器(associative container)**,用于存储**唯一且有序的元素**。

🧩 一、基本概念

✅ 特点:

  • 所有元素自动排序(默认从小到大)
  • 元素值唯一(不允许重复)
  • 内部实现为红黑树(Red-Black Tree)
  • 支持对数时间复杂度的插入、删除和查找操作:O(log n)

📦 二、头文件

#include 

🛠 三、基本用法

1. 定义 set

set s;              // 存储 int 类型,默认升序排列
set names;
set< int, greater  > s_desc;  // 按降序排列

2. 插入元素

s.insert(5);
s.insert(3);
s.insert(7);
s.insert(5);  // 不会重复插入

3. 查找元素

auto it = s.find(5);  // 返回迭代器
if (it != s.end()) {
    cout << "Found: " << *it << endl;
} else {
    cout << "Not found" << endl;
}

4. 删除元素

s.erase(3);           // 删除值为 3 的元素
s.erase(it);          // 删除迭代器指向的元素

5. 遍历 set

for (int x : s) {
    cout << x << " ";
}
// 或者使用迭代器
for (auto it = s.begin(); it != s.end(); ++it) {
    cout << *it << " ";
}

6. 判断是否为空 & 获取大小

if (s.empty()) {
    cout << "Set is empty";
}
cout << "Size: " << s.size();

🔍 四、常用函数总结

函数 说明
insert(x) 插入元素 x
erase(x) / erase(it) 删除值为 x 或迭代器 it 指向的元素
find(x) 查找 x,返回迭代器或 end()
count(x) 返回 x 是否存在(0 或 1)
lower_bound(x) 返回第一个不小于 x 的元素的迭代器
upper_bound(x) 返回第一个大于 x 的元素的迭代器
clear() 清空所有元素
size() 返回元素个数
empty() 判断是否为空

🧪 五、示例代码

#include 
#include 
using namespace std;

int main() {
    set s;

    s.insert(5);
    s.insert(3);
    s.insert(7);
    s.insert(3);  // 重复无效

    cout << "Elements: ";
    for (int x : s) cout << x << " ";  // 输出: 3 5 7
    cout << endl;

    if (s.find(5) != s.end())
        cout << "5 is in the set" << endl;

    s.erase(3);

    cout << "After erase 3: ";
    for (int x : s) cout << x << " ";  // 输出: 5 7
    cout << endl;

    return 0;
}

🔄 六、自定义比较函数(高级)

你可以自定义排序规则:

struct cmp {
    bool operator()(int a, int b) const {
        return a > b;  // 降序
    }
};

set s;
s.insert(5);
s.insert(3);
s.insert(7);

for (int x : s) cout << x << " ";  // 输出: 7 5 3

💡 七、应用场景

  • 去重并排序数据
  • 快速查找是否存在某个元素
  • 实现字典、排行榜等需要有序结构的场景
  • 配合 lower_bound/upper_bound 进行范围查询

如果你需要的是 multiset(允许重复元素)或者 unordered_set(无序但更快的哈希集合),也可以告诉我,我可以分别讲解它们的区别与用法。

</p>