std:: set
|
定义于头文件
<set>
|
||
|
template
<
class
Key,
|
(1) | |
|
namespace
pmr
{
template
<
|
(2) | (C++17 起) |
std::set
是一种关联容器,包含一组类型为
Key
的唯一对象且保持有序排序。排序通过键比较函数
Compare
实现。搜索、删除和插入操作具有对数复杂度。集合通常实现为
红黑树
。
凡是标准库使用 Compare 要求的地方,唯一性都是通过等价关系来确定的。不严格地说,两个对象 a 和 b 被认为是等价的,当且仅当两者互不小于对方: ! comp ( a, b ) && ! comp ( b, a ) 。
std::set
满足
Container
、
AllocatorAwareContainer
、
AssociativeContainer
和
ReversibleContainer
的要求。
std::set
的所有成员函数均为
constexpr
:可以在常量表达式求值过程中创建和使用
std::set
对象。
但
|
(since C++26) |
目录模板参数
成员类型
成员函数
观察器 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 返回用于比较键的函数 (公开成员函数) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
返回用于比较类型为 value_type 的对象中的键的函数 (公开成员函数) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
非成员函数
|
(C++20 中移除)
(C++20 中移除)
(C++20 中移除)
(C++20 中移除)
(C++20 中移除)
(C++20)
|
按字典序比较两个
set
的值
(函数模板) |
|
特化
std::swap
算法
(函数模板) |
|
|
(C++20)
|
擦除所有满足特定条件的元素
(函数模板) |
推导指引 |
(C++17 起) |
注释
成员类型
iterator
和
const_iterator
可能是同一类型的别名。这意味着使用这两种类型作为参数类型来定义一对函数重载可能会违反
单一定义规则
。由于
iterator
可转换为
const_iterator
,使用以
const_iterator
作为参数类型的单一函数即可实现相同功能。
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_containers_ranges
|
202202L
|
(C++23) | 容器的范围构造与插入 |
__cpp_lib_constexpr_set
|
202502L
|
(C++26) |
constexpr
std::set
|
示例
#include <algorithm> #include <iomanip> #include <iostream> #include <iterator> #include <set> #include <string_view> template<typename T> std::ostream& operator<<(std::ostream& out, const std::set<T>& set) { if (set.empty()) return out << "{}"; out << "{ " << *set.begin(); std::for_each(std::next(set.begin()), set.end(), [&out](const T& element) { out << ", " << element; }); return out << " }"; } int main() { std::set<int> set{1, 5, 3}; std::cout << set << '\n'; set.insert(2); std::cout << set << '\n'; set.erase(1); std::cout << set << "\n\n"; std::set<int> keys{3, 4}; for (int key : keys) { if (set.contains(key)) std::cout << set << " does contain " << key << '\n'; else std::cout << set << " doesn't contain " << key << '\n'; } std::cout << '\n'; std::string_view word = "element"; std::set<char> characters(word.begin(), word.end()); std::cout << "There are " << characters.size() << " unique characters in " << std::quoted(word) << ":\n" << characters << '\n'; }
输出:
{ 1, 3, 5 }
{ 1, 2, 3, 5 }
{ 2, 3, 5 }
{ 2, 3, 5 } does contain 3
{ 2, 3, 5 } doesn't contain 4
There are 5 unique characters in "element":
{ e, l, m, n, t }
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用标准 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 103 | C++98 | 迭代器允许修改键值 | 迭代器设为常量 |
| LWG 230 | C++98 |
Key
未要求为
CopyConstructible
(
Key
类型的键可能无法被构造)
|
Key
同时要求
为 CopyConstructible |
参见
|
按键排序的键集合
(类模板) |
|
|
(C++11)
|
通过键哈希的唯一键集合
(类模板) |
|
(C++23)
|
适配容器以提供按键排序的唯一键集合
(类模板) |