doc/notebook/docs/C++/9.set.md

72 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

1. **构造函数**
- `set()`:创建一个空集合。
- `set(const set& other)`:拷贝构造函数,用另一个集合初始化当前集合。
2. **赋值和交换**
- `operator=`:将一个集合赋值给另一个集合。
- `assign`:用特定数量的元素或范围内的元素替换集合的内容。
- `swap`:交换两个集合的内容。
3. **迭代器相关**
- `begin`:返回指向第一个元素的迭代器。
- `end`:返回指向最后一个元素之后的位置的迭代器。
- `rbegin`:返回指向最后一个元素的反向迭代器。
- `rend`:返回指向第一个元素之前的位置的反向迭代器。
4. **容量**
- `empty`:判断集合是否为空。
- `size`:返回集合中元素的数量。
- `max_size`:返回集合最大可容纳的元素数量。
5. **插入和访问元素**
- `insert`:插入一个元素或多个元素。
- `erase`:移除指定元素或范围内的元素。
- `clear`:移除集合的所有元素。
- `find`:查找指定元素的迭代器。
- `count`:统计指定元素在集合中出现的次数。
6. **其他操作**
- `lower_bound`:返回第一个不小于指定元素的迭代器。
- `upper_bound`:返回第一个大于指定元素的迭代器。
- `equal_range`:返回范围内与指定元素相等的上下界迭代器对。
下面是这些函数的示例用法:
```cpp
#include <iostream>
#include <set>
using namespace std;
int main() {
// 创建空集合
set<int> myset;
// 插入元素
myset.insert(5);
myset.insert(10);
myset.insert(3);
// 查找元素
auto it = myset.find(10);
if (it != myset.end()) {
cout << "Element found: " << *it << endl;
}
// 统计元素个数
int num = myset.count(5);
cout << "Number of 5s: " << num << endl;
// 移除元素
myset.erase(3);
// 输出元素
for (auto& num : myset) {
cout << num << " ";
}
cout << endl;
return 0;
}
```