一.set
std::set 是 C++ 标准模板库(STL)中的一种有序关联容器。它存储的元素都是唯一的,并且容器会按照元素的值自动进行排序。你可以把它想象成一个数学意义上的集合——每个元素只能出现一次,并且内部是天然有序的。
核心特点
-
有序性
所有元素在容器中总是按键(即元素本身)的升序排列。排序规则默认使用std::less<Key>,即<运算符,你也可以通过模板参数指定自定义的比较函数(例如std::greater实现降序)。 -
唯一性
容器中不允许存在两个相等的元素。判断相等的标准是比较结果不为true(即!(a < b) && !(b < a)),等价于“等价”而非“相同地址”。插入重复元素时,插入操作会被忽略。 -
关联性
元素是通过其值直接访问的,而不是像序列容器(如vector)那样通过位置索引。std::set将元素的值同时作为键,因此没有map那种分离的键值对。 -
不可直接修改
从std::set获得的迭代器是常量迭代器(const_iterator或类似行为),指向的元素是只读的。这是为了维护排序不变性——如果允许修改元素的值,就可能破坏内部的有序结构。若要修改一个元素,必须先删除旧值,再插入新值。 -
高效查找
由于采用平衡二叉搜索树(通常是红黑树)实现,std::set的核心操作(插入、删除、查找)均能达到对数时间复杂度($O(\log n)$)。C++11 起也支持哈希实现的std::unordered_set,但std::set仍以有序为特色。
1.1.构造函数
1. 空构造 (empty)
#include <iostream>
#include <set>
int main() {
// 默认构造一个空的 set,元素按升序排列(默认比较器 key_compare 为 less<int>)
std::set<int> s1;
s1.insert(30);
s1.insert(10);
s1.insert(20);
for (int x : s1) std::cout << x << " "; // 输出:10 20 30(已排序)
std::cout << std::endl;
// 也可以显式提供比较器和分配器,例如降序排列
std::set<int, std::greater<int>> s2; // 空 set,比较器改为 greater<int>
s2.insert(30);
s2.insert(10);
s2.insert(20);
for (int x : s2) std::cout << x << " "; // 输出:30 20 10(降序)
std::cout << std::endl;
return 0;
}

2. 范围构造 (range)
#include <iostream>
#include <set>
#include <vector>
int main() {
// 从数组构造 set
int arr[] = {5, 2, 8, 2, 1};
std::set<int> s1(arr, arr + 5); // 迭代器范围 [first, last)
for (int x : s1) std::cout << x << " "; // 输出:1 2 5 8(去重、排序)
std::cout << std::endl;
// 从 vector 构造,并指定降序比较器
std::vector<int> vec = {3, 1, 4, 1, 5};
std::set<int, std::greater<int>> s2(vec.begin(), vec.end());
for (int x : s2) std::cout << x << " "; // 输出:5 4 3 1
std::cout << std::endl;
return 0;
}

3. 拷贝构造 (copy)
#include <iostream>
#include <set>
int main() {
std::set<int> original = {10, 20, 30, 40};
// 拷贝构造:创建一个和 original 完全相同的新 set
std::set<int> copy(original);
original.insert(50); // 修改 original
copy.erase(40); // 修改 copy
std::cout << "original: ";
for (int x : original) std::cout << x << " "; // 10 20 30 40 50
std::cout << "\ncopy: ";
for (int x : copy) std::cout << x << " "; // 10 20 30(40被删除,没有50)
std::cout << std::endl;
return 0;
}

1.2.迭代器
其实这些迭代器还是和map的有点像

std::set 是 C++ 标准库中的有序关联容器,其内部元素始终按升序排列,且每个元素的值都是唯一的。
它提供的迭代器成员函数与 std::map 基本一致,但有一个关键区别:std::set 的所有迭代器(包括普通迭代器)实际上都是指向常量元素的迭代器——你无法通过任何迭代器修改元素的值,这是为了保证容器内部的有序结构不被破坏。
以下逐一说明每个迭代器函数在 std::set 中的具体作用:
begin
- 作用:返回一个指向容器中第一个元素的迭代器。
- 详细说明:std::set 的元素按键升序排列,因此 begin() 指向键值最小的元素。你可以通过此迭代器开始正向遍历整个集合。如果容器为空,则返回的迭代器与 end() 相等。
- 迭代器类型:普通迭代器(但解引用后得到 const 引用,实际等同于常量迭代器)。
end
- 作用:返回一个指向容器末尾元素之后的迭代器。
- 详细说明:该迭代器不指向任何有效元素,仅用作遍历的终止标志。例如在 for 循环中,当正向迭代器等于 end() 时表示遍历结束。它不能解引用。
- 迭代器类型:普通迭代器(仅作哨兵)。
#include <iostream>
#include <set>
int main() {
// 1. 非空 set:元素自动升序排序
std::set<int> s = {5, 1, 9, 3, 7};
// 使用 begin() 和 end() 正向遍历
std::cout << "Set elements (sorted): ";
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it << " "; // *it 为 const int&,不可修改
}
std::cout << std::endl; // 输出:1 3 5 7 9
// 2. begin() 指向最小元素
if (!s.empty()) {
std::cout << "Smallest element: " << *s.begin() << std::endl; // 1
}
// 3. 空 set:begin() 与 end() 相等
std::set<double> empty_set;
if (empty_set.begin() == empty_set.end()) {
std::cout << "Empty set: begin() equals end()" << std::endl;
}
return 0;
}

- begin() 返回指向第一个元素(即键值最小的元素)的迭代器,end() 返回末尾哨兵迭代器,两者配合可实现完整遍历。
- 当集合为空时,begin() 与 end() 相等,此时不能解引用 begin()。
- 通过 *s.begin() 可以快速获取最小元素。

rbegin
- 作用:返回一个指向反向迭代器的第一个元素的迭代器。
- 详细说明:反向迭代器将容器的逻辑顺序反转——rbegin() 对应正向容器中的最后一个元素(即键值最大的元素)。通过反向迭代器可以从大到小遍历 set。
- 迭代器类型:反向迭代器(解引用后得到 const 引用,实际等同于常量迭代器)。
rend
- 作用:返回一个指向反向迭代器末尾元素之后的迭代器。
- 详细说明:它是反向遍历的结束标志,对应正向容器中第一个元素之前的位置。与 end() 类似,它不可解引用,仅用于比较。
- 迭代器类型:反向迭代器。
#include <iostream>
#include <set>
int main() {
// 1. 非空 set:元素自动升序,但反向遍历会得到降序
std::set<int> s = {5, 1, 9, 3, 7};
// 使用 rbegin() 和 rend() 反向遍历(从大到小)
std::cout << "Set elements in reverse (largest to smallest): ";
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
std::cout << *rit << " "; // *rit 为 const int&,不可修改
}
std::cout << std::endl; // 输出:9 7 5 3 1
// 2. rbegin() 指向最大元素
if (!s.empty()) {
std::cout << "Largest element: " << *s.rbegin() << std::endl; // 9
}
// 3. 空 set:rbegin() 与 rend() 相等
std::set<double> empty_set;
if (empty_set.rbegin() == empty_set.rend()) {
std::cout << "Empty set: rbegin() equals rend()" << std::endl;
}
return 0;
}
- rbegin() 返回指向最大元素(正向最后一个元素)的反向迭代器,rend() 返回指向第一个元素之前位置的反向哨兵。
- 反向迭代器的递增 (++rit) 会使其在正向容器中向前移动(即从大到小遍历)。
- 空集合时,rbegin() 与 rend() 相等,不可解引用。
- 反向迭代器可通过 base() 成员函数获得对应的正向迭代器,两者存在偏移关系(rit.base() 指向 rit 所指向元素的下一个位置),这是标准库的常见设计。

cbegin
- 作用:返回一个指向容器中第一个元素的常量迭代器(const_iterator)。
- 详细说明:与 begin() 功能完全相同,但强制返回常量迭代器,明确表明不允许修改所指向的元素。在 std::set 中,普通迭代器本身已具备常量性质,但 cbegin() 在泛型编程或接口设计时能更清晰地传达只读意图。
- 迭代器类型:常量双向迭代器。
cend
- 作用:返回一个指向容器末尾元素之后的常量迭代器。
- 详细说明:与 end() 功能相同,但返回常量迭代器,作为只读遍历的结束条件。
- 迭代器类型:常量双向迭代器。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {5, 1, 9, 3, 7};
// 1. 使用 cbegin() 和 cend() 进行只读遍历
std::cout << "Set elements (const traversal): ";
for (auto it = s.cbegin(); it != s.cend(); ++it) {
std::cout << *it << " "; // *it 为 const int&,不可修改
// *it = 100; // 编译错误:常量迭代器禁止写入
}
std::cout << std::endl; // 输出:1 3 5 7 9
// 2. cbegin() 与 begin() 的区别(set 中两者行为类似,但类型不同)
std::set<int>::iterator it1 = s.begin(); // 普通迭代器(但不可修改元素)
std::set<int>::const_iterator it2 = s.cbegin(); // 常量迭代器
// 在 set 中,普通迭代器也无法修改元素,但 cbegin() 显式表明只读意图
// *it1 = 200; // 仍然编译错误,set 的 iterator 本质也是 const
// 3. 空 set 时,cbegin() == cend()
std::set<double> empty_set;
if (empty_set.cbegin() == empty_set.cend()) {
std::cout << "Empty set: cbegin() equals cend()" << std::endl;
}
// 4. 泛型编程中优先使用 cbegin()(C++11 起可用)
auto print_set = [](const std::set<int>& st) {
// 传入 const 引用时,st.begin() 实际返回 const_iterator
// 但显式使用 st.cbegin() 更清晰
for (auto it = st.cbegin(); it != st.cend(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
};
print_set(s); // 输出:1 3 5 7 9
return 0;
}
- cbegin() 返回常量迭代器(const_iterator),指向键值最小的元素。
- cend() 返回常量迭代器,指向末尾哨兵,用作只读遍历的结束条件。
- 在 std::set 中,普通迭代器(iterator)解引用后也得到 const 引用,但 cbegin() 能更明确地表达只读语义,尤其在泛型代码或接受 const 容器引用时。
- 空集合时,cbegin() 与 cend() 相等。
- 自 C++11 起,cbegin/cend 成为标准成员函数,C++14 还增加了非成员函数版本(std::cbegin/cend)。

crbegin
- 作用:返回一个指向反向迭代器第一个元素的常量反向迭代器(const_reverse_iterator)。
- 详细说明:它对应正向容器中最后一个元素(最大值),但返回的是常量反向迭代器,禁止通过它修改元素。用于只读的反向遍历。
- 迭代器类型:常量反向迭代器。
crend
- 作用:返回一个指向反向迭代器末尾元素之后的常量反向迭代器。
- 详细说明:作为只读反向遍历的结束标志,对应正向容器第一个元素之前的位置。不可解引用。
- 迭代器类型:常量反向迭代器。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {5, 1, 9, 3, 7};
// 1. 使用 crbegin() 和 crend() 进行只读反向遍历(从大到小)
std::cout << "Set elements in reverse (const reverse traversal): ";
for (auto rit = s.crbegin(); rit != s.crend(); ++rit) {
std::cout << *rit << " "; // *rit 为 const int&,不可修改
// *rit = 100; // 编译错误:常量反向迭代器禁止写入
}
std::cout << std::endl; // 输出:9 7 5 3 1
// 2. crbegin() 与 rbegin() 的区别(类型不同)
std::set<int>::reverse_iterator rit1 = s.rbegin(); // 普通反向迭代器
std::set<int>::const_reverse_iterator rit2 = s.crbegin(); // 常量反向迭代器
// 在 set 中,普通反向迭代器也无法修改元素,但 crbegin() 显式表明只读意图
// *rit1 = 200; // 仍然编译错误,set 的反向迭代器本质也是 const
// 3. 空 set 时,crbegin() == crend()
std::set<double> empty_set;
if (empty_set.crbegin() == empty_set.crend()) {
std::cout << "Empty set: crbegin() equals crend()" << std::endl;
}
return 0;
}

重要补充:std::set 迭代器的特殊性质
所有迭代器均为“只读”:由于 std::set 的元素本身就是键,修改元素会破坏容器内部的有序二叉搜索树结构,因此标准库规定:即使是普通迭代器(iterator),解引用后获得的也是 const 引用。这意味着你无法通过 begin()、rbegin() 等返回的迭代器修改元素值。这也是 set 与 map 的重要区别(map 允许通过迭代器修改值 mapped_type,但不允许修改键 key_type)。
迭代器类别:所有迭代器都属于双向迭代器,支持 ++ 和 -- 操作,但不支持随机访问(如 it + n)。
失效规则:std::set 的迭代器在插入和删除操作中具有高度的稳定性——插入元素不会使任何已有迭代器失效;删除元素仅使指向被删元素的迭代器失效,其他迭代器依然有效。
1.3.set的容量操作
empty()
- 用于检测 std::set 容器是否为空。
- 若容器中没有任何元素,返回 true;否则返回 false。
- 该函数不修改容器,且执行时间为常数复杂度O(1)。
- 通常在遍历或访问元素前使用,避免对空容器进行操作。
size()
- 返回当前 std::set 容器中不重复元素的总个数,返回值类型为 size_t。
- 同样为常数复杂度O(1),因为容器内部维护了元素计数。
- 适用于需要知道集合大小、循环控制或统计场景。
我们直接看例子
#include <iostream>
#include <set>
int main() {
// 1. 初始状态:空集合
std::set<int> s;
std::cout << "Initially:\n";
std::cout << " empty() = " << std::boolalpha << s.empty() // true
<< ", size() = " << s.size() << "\n\n"; // 0
// 2. 插入元素
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(20); // 重复插入无效,size 不变
std::cout << "After insertions:\n";
std::cout << " empty() = " << s.empty() // false
<< ", size() = " << s.size() << "\n\n"; // 3
// 3. 删除元素
s.erase(20);
std::cout << "After erasing 20:\n";
std::cout << " empty() = " << s.empty() // false
<< ", size() = " << s.size() << "\n\n"; // 2
// 4. 清空容器
s.clear();
std::cout << "After clear():\n";
std::cout << " empty() = " << s.empty() // true
<< ", size() = " << s.size() << std::endl; // 0
return 0;
}

1.4.set的成员修改操作
insert
向 std::set 中插入元素。由于元素必须唯一,若容器中已存在等价元素,则插入失败。
- 单元素插入:接受一个值,返回 一个pair<iterator, bool>,iterator 指向新插入元素或已存在的等价元素,bool 表示是否成功插入(true 为新插入)。
- 带提示插入:额外接受一个迭代器作为插入位置提示,返回迭代器,指向实际插入或已存在的元素。
- 范围插入:接受一对迭代器,将另一容器中的元素逐一插入。
插入后容器自动保持有序。
#include <iostream>
#include <set>
#include <vector>
int main() {
std::set<int> s;
// ---------- 1. 单元素插入 ----------
// 返回 pair<iterator, bool>
auto result1 = s.insert(10);
std::cout << "Insert 10: "
<< (result1.second ? "success" : "failed")
<< ", value = " << *result1.first << std::endl; // success, 10
auto result2 = s.insert(20);
std::cout << "Insert 20: "
<< (result2.second ? "success" : "failed")
<< ", value = " << *result2.first << std::endl; // success, 20
auto result3 = s.insert(10); // 重复插入
std::cout << "Insert 10 again: "
<< (result3.second ? "success" : "failed")
<< ", value = " << *result3.first << std::endl; // failed, 10
std::cout << "Set after single inserts: ";
for (int x : s) std::cout << x << ' '; // 10 20
std::cout << "\n\n";
// ---------- 2. 带提示插入 ----------
// 接受迭代器作为提示位置,返回指向插入元素的迭代器
auto it = s.find(20); // 正向迭代器,指向20
auto hint_it = s.insert(it, 15); // 提示位置在20之前,适合插入15
std::cout << "Insert 15 with hint: inserted = " << *hint_it << std::endl;
// 提示位置错误也不影响插入正确性(但可能性能较低)
auto bad_hint = s.insert(s.begin(), 25); // 25应排在20之后,但提示位置在最前
std::cout << "Insert 25 with bad hint: inserted = " << *bad_hint << std::endl;
std::cout << "Set after hint inserts: ";
for (int x : s) std::cout << x << ' '; // 10 15 20 25
std::cout << "\n\n";
// ---------- 3. 范围插入 ----------
std::vector<int> vec = {5, 30, 5, 15, 40}; // 5重复,15已存在
s.insert(vec.begin(), vec.end()); // 插入整个vector(自动去重)
std::cout << "Set after range insert: ";
for (int x : s) std::cout << x << ' '; // 5 10 15 20 25 30 40
std::cout << "\n";
return 0;
}

erase
从 std::set 中移除元素。
- 按迭代器删除:接受指向待删元素的迭代器,返回指向被删元素之后元素的迭代器(C++11 起)。
- 按键值删除:接受一个键值,删除键等价的元素,返回被删除的元素个数(0 或 1,因键唯一)。
- 按范围删除:接受两个迭代器,删除该范围内的所有元素,返回指向最后一个被删元素之后元素的迭代器。
删除后其他迭代器不受影响。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50, 60, 70};
std::cout << "Initial set: ";
for (int x : s) std::cout << x << ' ';
std::cout << "\n\n";
// ---------- 1. 按键值删除 ----------
size_t n = s.erase(30); // 删除键值为30的元素
std::cout << "Erase 30: removed " << n << " element(s)\n"; // 输出 1
n = s.erase(100); // 尝试删除不存在的元素
std::cout << "Erase 100: removed " << n << " element(s)\n"; // 输出 0
std::cout << "After key erasures: ";
for (int x : s) std::cout << x << ' '; // 10 20 40 50 60 70
std::cout << "\n\n";
// ---------- 2. 按迭代器删除 ----------
auto it = s.find(50); // 指向50的迭代器
if (it != s.end()) {
auto next_it = s.erase(it); // 删除50,返回指向下一个元素的迭代器(60)
std::cout << "Erased 50, next element is " << *next_it << "\n";
}
std::cout << "After iterator erase: ";
for (int x : s) std::cout << x << ' '; // 10 20 40 60 70
std::cout << "\n\n";
// ---------- 3. 按范围删除 ----------
auto first = s.find(40); // 指向40
auto last = s.find(70); // 指向70
// 删除 [40, 70) 区间内的元素,即40和60(70不被删除)
auto after_range = s.erase(first, last);
std::cout << "Erased range [40, 70), next element is " << *after_range << "\n"; // 70
std::cout << "After range erase: ";
for (int x : s) std::cout << x << ' '; // 10 20 70
std::cout << "\n";
return 0;
}
- 按键值删除:返回被删除的元素个数(std::set 中为 0 或 1)。即使键不存在也不会出错。
- 按迭代器删除:必须传入指向有效元素的迭代器,否则行为未定义。返回指向被删元素下一个元素的迭代器(C++11 起)。可用于循环中安全删除当前元素并继续遍历。
- 按范围删除:删除左闭右开区间 [first, last) 内的所有元素,返回指向 last 的迭代器(即最后一个被删元素之后的位置)。
- 所有 erase 操作都不会使指向其他元素的迭代器失效(仅被删元素的迭代器失效),这是 std::set 的重要特性。

swap
交换当前 std::set 与另一个同类型 std::set 容器的全部内容。
- 交换包括所有元素、排序准则、分配器等内部数据。
- 该操作是常数复杂度,仅交换内部指针,不涉及元素拷贝或移动。
- 交换后原迭代器仍指向相同元素,但已归属对方容器。
成员函数 swap 与 std::swap 特化版本效果相同。
#include <iostream>
#include <set>
int main() {
// 创建两个不同内容的 set
std::set<int> set1 = {1, 2, 3};
std::set<int> set2 = {10, 20, 30, 40};
std::cout << "Before swap:\n";
std::cout << "set1: ";
for (int x : set1) std::cout << x << ' ';
std::cout << "\nset2: ";
for (int x : set2) std::cout << x << ' ';
std::cout << "\n\n";
// 获取指向 set1 第一个元素的迭代器
auto it = set1.begin(); // 指向 set1 中的 1
// 执行 swap:交换两个 set 的全部内容(包括比较器、分配器等)
set1.swap(set2);
std::cout << "After swap:\n";
std::cout << "set1: ";
for (int x : set1) std::cout << x << ' '; // 现在 set1 拥有原 set2 的元素
std::cout << "\nset2: ";
for (int x : set2) std::cout << x << ' '; // set2 拥有原 set1 的元素
std::cout << "\n\n";
// 原先指向 set1 的迭代器 it 现在指向的是哪个容器的元素?
// 迭代器本身仍然有效,并且指向的是同一个元素(1),
// 但该元素现在属于 set2(因为 set1 和 set2 交换了内容)
std::cout << "Iterator *it = " << *it << '\n'; // 仍然输出 1
std::cout << "it belongs to: ";
// 通过比较迭代器与容器的 begin/end 来判断它属于哪个容器
if (it != set2.end() && *it == *set2.begin())
std::cout << "set2 (since it points to " << *it << " which is now in set2)\n";
else
std::cout << "set1\n";
return 0;
}
- swap() 是常数复杂度 O(1),仅交换内部数据结构指针,不复制或移动任何元素。
- 交换后,两个容器的元素完全互换,包括排序准则和分配器(若不同则行为未定义,通常要求同类型)。
- 原迭代器仍然指向原来的元素,但这些元素已属于另一个容器。迭代器本身并未失效,依然可以安全解引用,但其关联的容器对象已改变。
- std::swap(set1, set2) 的非成员函数版本在 C++11 后也具备 O(1) 复杂度(通过特化调用成员 swap),效果与成员函数完全相同。

clear
立即移除 std::set 中的所有元素。
- 调用后容器大小为 0,所有元素被销毁。
- 所有指向元素的迭代器、引用、指针均失效。
- 容器本身仍可继续使用(如插入新元素)。
- 复杂度线性于元素个数(需逐一析构),但不保证释放已分配的内存(与 vector 不同,set 无 capacity 概念)。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
std::cout << "Before clear: size = " << s.size() << ", elements: ";
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
// 获取一个指向元素的迭代器
auto it = s.find(30);
std::cout << "Iterator points to: " << *it << '\n'; // 30
// ---------- 调用 clear() ----------
s.clear();
std::cout << "After clear: size = " << s.size() << ", empty? "
<< std::boolalpha << s.empty() << '\n';
// 迭代器 it 现已失效(指向已被销毁的元素)
// 解引用已失效的迭代器是未定义行为(下面这行在正确程序中应避免)
// std::cout << *it; // 不要这样做!
// clear 后容器仍可继续使用
s.insert(100);
s.insert(200);
std::cout << "After re-insert: ";
for (int x : s) std::cout << x << ' '; // 100 200
std::cout << '\n';
return 0;
}

emplace
在 std::set 中就地构造一个新元素,避免临时对象的拷贝或移动。
- 接受与元素构造函数匹配的参数包,在容器内部直接构造元素。
- 插入位置由容器自动根据排序规则确定。
- 返回 pair<iterator, bool>,含义与 insert 相同。
- 对于构造成本较高的类型,此函数可显著提升性能。
#include <iostream>
#include <set>
// 一个自定义类,用于展示构造/拷贝开销
struct Person {
std::string name;
int age;
// 构造函数(输出日志以便观察)
Person(std::string n, int a) : name(std::move(n)), age(a) {
std::cout << " 构造函数: " << name << "\n";
}
// 拷贝构造函数(输出日志)
Person(const Person& other) : name(other.name), age(other.age) {
std::cout << " Copy 构造函数: " << name << "\n";
}
// 移动构造函数(输出日志)
Person(Person&& other) noexcept : name(std::move(other.name)), age(other.age) {
std::cout << " Move 构造函数: " << name << "\n";
}
// 用于 set 排序(按姓名)
bool operator<(const Person& other) const {
return name < other.name;
}
};
int main() {
std::cout << "--- emplace 构造 ---\n";
std::set<Person> people;
// emplace:在容器内部直接构造 Person("Alice", 30)
auto result = people.emplace("Alice", 30);
std::cout << "Inserted: " << std::boolalpha << result.second
<< ", element: " << result.first->name << "\n\n";
std::cout << "--- emplace 重复键(插入失败)---\n";
// 尝试插入已存在的键("Alice", 25),emplace 不会构造临时对象
auto result2 = people.emplace("Alice", 25); // 不会调用任何构造函数
std::cout << "Inserted: " << result2.second
<< ", element: " << result2.first->name << "\n\n";
std::cout << "--- insert 临时对象 ---\n";
// insert 需要传入已构造的 Person 对象,产生一次临时对象构造
Person bob("Bob", 40);
people.insert(bob); // 拷贝构造临时对象到容器
std::cout << "--- insert 移动 ---\n";
people.insert(Person("Charlie", 50)); // 构造临时 + 移动(或拷贝)进容器
std::cout << "\nFinal set contents:\n";
for (const auto& p : people)
std::cout << " " << p.name << " (" << p.age << ")\n";
return 0;
}

emplace_hint
带插入位置提示的就地构造版本。
- 第一个参数是一个迭代器,用作插入位置的提示;后续参数为元素构造参数。
- 若提示准确(即正好在应插入位置之前),插入操作可达到均摊常数时间复杂度;否则退化为普通插入的对数复杂度。
- 返回一个迭代器,指向新插入的元素或已存在的等价元素。
- 提示位置不影响正确性,仅用于性能优化。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
// ---------- 1. 准确提示 ----------
// 要插入 25,应位于 20 和 30 之间,提示位置指向 30(插入点之后)
auto hint = s.find(30); // 迭代器指向 30
auto it = s.emplace_hint(hint, 25); // 提示准确 → 均摊常数复杂度
std::cout << "Inserted 25 (accurate hint): " << *it << '\n';
// ---------- 2. 不准确提示 ----------
// 要插入 35,但错误地提示在 begin() 位置(最小值 10)
auto bad_hint = s.begin(); // 指向 10
auto it2 = s.emplace_hint(bad_hint, 35);
std::cout << "Inserted 35 (bad hint): " << *it2 << '\n';
// ---------- 3. 插入已存在的元素 ----------
auto it3 = s.emplace_hint(s.begin(), 20); // 20 已存在
std::cout << "Insert existing 20: " << *it3
<< " (no insertion, size=" << s.size() << ")\n";
// 输出最终集合
std::cout << "\nFinal set: ";
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}

1.5.set的元素查找操作
find
- 在 std::set 中查找指定值的元素。
- 若存在,返回指向该元素的迭代器;若不存在,返回 end()。由于元素唯一,最多找到一个匹配。
- 复杂度为对数级别O(log n)。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
// ---------- 查找存在的元素 ----------
auto it = s.find(30);
if (it != s.end()) {
std::cout << "Found: " << *it << '\n'; // 输出 30
}
// ---------- 查找不存在的元素 ----------
it = s.find(99);
if (it == s.end()) {
std::cout << "99 not found in set\n";
}
// ---------- 利用 find 结果直接操作 ----------
// 删除找到的元素
it = s.find(20);
if (it != s.end()) {
s.erase(it); // 安全删除
std::cout << "Removed 20\n";
}
// 输出最终集合
std::cout << "Final set: ";
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}

count
- 统计容器中与指定值等价的元素个数。
- 由于 std::set 不允许重复元素,返回值只能是 0(不存在)或 1(存在)。
- 复杂度为对数级别。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {5, 10, 15, 20, 25};
// ---------- 存在的元素 ----------
int key = 15;
if (s.count(key)) { // 返回 1(真)
std::cout << key << " exists in set (count = 1)\n";
}
// ---------- 不存在的元素 ----------
key = 99;
std::cout << key << " appears " << s.count(key) << " times\n"; // 0
// ---------- 在条件表达式中的典型用法 ----------
std::cout << "Inserting 30...\n";
if (!s.count(30)) { // 如果不存在
s.insert(30);
std::cout << "30 inserted\n";
}
// 输出最终集合
std::cout << "Set contains: ";
for (int x : s) std::cout << x << ' ';
std::cout << '\n';
return 0;
}

lower_bound
- 返回指向容器中第一个不小于指定值的元素的迭代器。
- 即首个满足 元素 ≥ val 的元素;若所有元素都小于 val,返回 end()。
- 复杂度为对数级别。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
// ---------- 查找存在且等于边界的元素 ----------
auto it = s.lower_bound(30);
if (it != s.end()) {
std::cout << "lower_bound(30) = " << *it << '\n'; // 30
}
// ---------- 查找介于两个元素之间的值 ----------
it = s.lower_bound(35); // 35 不在集合中,应返回第一个 ≥35 的元素
std::cout << "lower_bound(35) = " << *it << '\n'; // 40
// ---------- 查找小于所有元素的值 ----------
it = s.lower_bound(5); // 5 < 最小元素 10
std::cout << "lower_bound(5) = " << *it << '\n'; // 10
// ---------- 查找大于所有元素的值 ----------
it = s.lower_bound(60); // 60 > 最大元素 50
if (it == s.end()) {
std::cout << "lower_bound(60) = end()\n";
}
return 0;
}

upper_bound
- 返回指向容器中第一个>指定值的元素的迭代器。
- 若不存在大于 val 的元素,返回 end()。常与 lower_bound 配合确定值 val 的存在范围。
- 复杂度为对数级别。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
// ---------- 查找大于某值的第一个元素 ----------
auto it = s.upper_bound(30);
if (it != s.end()) {
std::cout << "upper_bound(30) = " << *it << '\n'; // 40(第一个大于30的元素)
}
// ---------- 值介于两个元素之间 ----------
it = s.upper_bound(35); // 35不在集合中,第一个大于35的元素是40
std::cout << "upper_bound(35) = " << *it << '\n'; // 40
// ---------- 值小于最小元素 ----------
it = s.upper_bound(5); // 5 < 10,第一个大于5的元素是10
std::cout << "upper_bound(5) = " << *it << '\n'; // 10
// ---------- 值大于最大元素 ----------
it = s.upper_bound(60); // 60 > 50,没有元素大于60
if (it == s.end()) {
std::cout << "upper_bound(60) = end()\n";
}
// ---------- 与 lower_bound 配合:判断元素是否存在 ----------
int val = 30;
auto low = s.lower_bound(val); // 第一个 ≥30 的元素(30本身)
auto up = s.upper_bound(val); // 第一个 >30 的元素(40)
if (low != s.end() && *low == val) {
std::cout << val << " exists in the set\n";
std::cout << "Range of " << val << " is [" << *low << ", " << *up << ")\n";
} else {
std::cout << val << " not found\n";
}
return 0;
}

equal_range
- 返回一个迭代器对(pair<iterator, iterator>),表示容器中所有与指定值等价的元素范围。
- 对于 std::set,该范围要么为空(first == second),要么恰好包含一个元素。
- 相当于同时调用 lower_bound 和 upper_bound,更高效。复杂度为对数级别。
#include <iostream>
#include <set>
int main() {
std::set<int> s = {10, 20, 30, 40, 50};
// ---------- 查找存在的键 ----------
int key = 30;
auto range = s.equal_range(key);
// range.first = lower_bound(key) -> 指向第一个 >=30 的元素(30)
// range.second = upper_bound(key) -> 指向第一个 >30 的元素(40)
std::cout << "equal_range(" << key << "):\n";
std::cout << " first = " << *range.first << '\n'; // 30
std::cout << " second = " << *range.second << '\n'; // 40
std::cout << " range contains: ";
for (auto it = range.first; it != range.second; ++it) {
std::cout << *it << ' '; // 仅输出 30
}
std::cout << "\n\n";
// ---------- 查找不存在的键(介于元素之间)----------
key = 35;
range = s.equal_range(key);
// lower_bound(35) = 指向40
// upper_bound(35) = 也指向40(因为40 >35)
// 此时 range.first == range.second,范围为空
if (range.first == range.second) {
std::cout << "equal_range(" << key << "):\n";
std::cout << " first = second = " << *range.first << " (end? "
<< (range.first == s.end() ? "yes" : "no") << ")\n";
std::cout << " range is empty\n\n";
}
// ---------- 查找不存在的键(大于所有元素)----------
key = 60;
range = s.equal_range(key);
// lower_bound(60) = end()
// upper_bound(60) = end()
// 两者均等于 end()
if (range.first == s.end() && range.second == s.end()) {
std::cout << "equal_range(" << key << "): both first and second are end()\n";
}
return 0;
}

二. multiset
我们说说最核心的区别:
std::set
不允许重复元素。容器中的所有元素彼此“等价”(根据比较规则,!(a < b) && !(b < a))的元素只能存在一个。这是集合的数学特性。
std::multiset
允许重复元素。同一个值可以出现多次,每个副本被视为独立的元素,它们彼此等价,但容器会为每个副本分配独立的存储节点。插入顺序不会影响排序,但相同值的元素在容器中一定是相邻存储的。
其他的说实话区别其实很小。
2.1.构造函数
那么我们就直接看看
#include <iostream>
#include <set> // std::multiset
#include <vector>
int main() {
// ---------- 1. 空构造 ----------
// 创建一个空的 multiset,元素按升序排列(默认比较器)
std::multiset<int> ms1;
ms1.insert(30);
ms1.insert(10);
ms1.insert(20);
ms1.insert(30); // 插入重复元素
ms1.insert(20);
std::cout << "ms1 (empty constructed): ";
for (int x : ms1) std::cout << x << ' ';
std::cout << "(size = " << ms1.size() << ")\n"; // 10 20 20 30 30
// ---------- 2. 范围构造 ----------
// 从数组或其它容器构造 multiset,自动排序并保留重复
int arr[] = {5, 2, 8, 2, 1, 5, 3};
std::multiset<int> ms2(arr, arr + 7); // 使用数组范围
std::cout << "ms2 (range constructed): ";
for (int x : ms2) std::cout << x << ' ';
std::cout << "(size = " << ms2.size() << ")\n"; // 1 2 2 3 5 5 8
// 也可以从 vector 构造
std::vector<int> vec = {10, 30, 20, 30, 10};
std::multiset<int> ms3(vec.begin(), vec.end());
std::cout << "ms3 (from vector): ";
for (int x : ms3) std::cout << x << ' ';
std::cout << "(size = " << ms3.size() << ")\n"; // 10 10 20 30 30
// ---------- 3. 拷贝构造 ----------
// 复制整个 multiset,新容器拥有独立副本
std::multiset<int> ms4(ms2); // 拷贝构造
std::cout << "ms4 (copy of ms2): ";
for (int x : ms4) std::cout << x << ' ';
std::cout << "(size = " << ms4.size() << ")\n"; // 与 ms2 相同
// 修改原容器不影响拷贝
ms2.insert(100);
std::cout << "After ms2.insert(100), ms2: ";
for (int x : ms2) std::cout << x << ' ';
std::cout << "\nms4 unchanged: ";
for (int x : ms4) std::cout << x << ' ';
std::cout << '\n';
return 0;
}

2.2.成员修改操作
std::set 与 std::multiset 共享大量相同的接口名称和语法,但由于 std::multiset 允许键重复,许多成员函数的行为产生了本质差异。
insert
向 std::multiset 中插入新元素。
- 单元素插入:接受一个元素值,始终成功,不会因元素已存在而失败。返回一个迭代器(C++11 起返回 iterator,C++98 返回 iterator 但语义相同),指向新插入的元素。
- 带提示插入:额外接受一个迭代器作为插入位置提示。也始终成功,返回指向新元素的迭代器。提示仅用于性能优化,若提示准确(应插入位置的前驱),可达到均摊常数时间复杂度。
- 范围插入:接受一对迭代器,将另一容器中的元素逐一插入当前 multiset,所有元素都会被插入,即使存在重复值。
插入后容器自动按键的升序排列,相同键的元素会相邻存储,且相对顺序与插入顺序一致(C++11 起保证)。
#include <iostream>
#include <set>
#include <vector>
int main() {
std::multiset<int> ms;
// ---------- 1. 单元素插入 ----------
// 返回迭代器,指向新插入的元素(即使已有相同值)
auto it1 = ms.insert(10);
std::cout << "Inserted 10, iterator points to: " << *it1 << '\n';
auto it2 = ms.insert(20);
auto it3 = ms.insert(10); // 插入重复值
std::cout << "Inserted another 10, iterator points to: " << *it3 << '\n';
// 两个 10 的迭代器不同(指向不同节点),元素相邻存储
std::cout << "After single inserts: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n"; // 10 10 20
// ---------- 2. 带提示插入 ----------
// 准确提示:应在 20 之前插入 15(提示位置为 20 的迭代器)
auto hint = ms.find(20); // 指向第一个 20
auto it4 = ms.insert(hint, 15);
std::cout << "Inserted 15 with accurate hint: " << *it4 << '\n';
// 不准确提示:应在 10 之后插入 25,但提示位置为 begin()(指向第一个10)
auto bad_hint = ms.begin();
auto it5 = ms.insert(bad_hint, 25);
std::cout << "Inserted 25 with bad hint: " << *it5 << '\n';
// 插入重复值带提示
auto it6 = ms.insert(ms.end(), 10); // 提示在末尾,实际插入位置在第二个10之后
std::cout << "Inserted another 10 with hint: " << *it6 << '\n';
std::cout << "After hint inserts: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n"; // 10 10 10 15 20 25
// ---------- 3. 范围插入 ----------
std::vector<int> vec = {5, 15, 5, 30, 25};
ms.insert(vec.begin(), vec.end()); // 所有元素都被插入(包括重复)
std::cout << "After range insert: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n"; // 5 5 10 10 10 15 15 20 25 25 30
return 0;
}

erase
从 std::multiset 中移除元素。根据调用方式不同,行为如下:
- 按键值删除:size_type erase(const key_type& key);——删除所有与 key 等价的元素(即键值等于 key 的所有副本),返回实际被删除的元素个数(可以是 0,1,2,…)。这是与 std::set 最显著的区别——set 最多删除一个。
- 按迭代器删除单个元素:iterator erase(const_iterator pos);——删除 pos 指向的单个元素(可以是某个重复键中的一个特定副本),返回指向被删元素之后元素的迭代器。
- 按范围删除:iterator erase(const_iterator first, const_iterator last);——删除 [first, last) 范围内的所有元素,返回指向最后一个被删元素之后元素的迭代器(即 last)。
删除操作仅使指向被删元素的迭代器失效,其他迭代器保持不变。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含多个重复值
std::multiset<int> ms = {10, 20, 10, 30, 20, 40, 10, 50};
std::cout << "Initial multiset: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 1. 按键删除 ----------
// 删除所有值为 10 的元素,返回删除的个数
size_t n = ms.erase(10);
std::cout << "Erased " << n << " element(s) with key 10\n"; // 3
std::cout << "After erase(10): ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// 尝试删除不存在的键
n = ms.erase(99);
std::cout << "Erased " << n << " element(s) with key 99\n\n"; // 0
// ---------- 2. 按迭代器删除(单个元素)----------
// 找到第一个值为 20 的元素并删除
auto it = ms.find(20); // 指向第一个 20
if (it != ms.end()) {
auto next_it = ms.erase(it); // 删除该元素,返回指向下一个元素的迭代器
std::cout << "Erased single 20, next element is " << *next_it << '\n';
}
std::cout << "After iterator erase: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 3. 按范围删除 ----------
// 删除区间 [first, last) —— 删除所有 30 到 40 之间的元素(包括30但不包括40)
auto first = ms.lower_bound(30); // 指向第一个 >=30 的元素
auto last = ms.lower_bound(40); // 指向第一个 >=40 的元素(即40本身)
auto after_range = ms.erase(first, last); // 删除 [30,40) 内的所有元素(即30)
std::cout << "Erased range [30,40), next element is " << *after_range << '\n'; // 40
std::cout << "After range erase: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n";
return 0;
}

swap
交换当前 std::multiset 与另一个同类型 std::multiset 容器的全部内容。
- 交换内容包括:所有存储的元素、键比较函数对象、分配器等内部数据结构。
- 复杂度为常数时间,仅交换内部指针,不涉及任何元素拷贝或移动。
- 交换后,两个容器原有的迭代器、引用和指针仍然有效,但指向的元素已归属对方容器。
- 成员函数 swap 与非成员函数 std::swap 特化版本等效。
clear
立即移除 std::multiset 中的所有元素,使容器变为空状态(size() == 0)。
- 所有元素被销毁,内存可能被释放(由实现决定,但节点通常归还给分配器)。
- 所有指向容器元素的迭代器、引用和指针均失效。
- 容器本身仍可继续使用(如插入新元素)。
- 复杂度线性于当前元素个数(需逐一析构)。
#include <iostream>
#include <set>
int main() {
// 创建两个不同的 multiset(允许重复元素)
std::multiset<int> ms1 = {1, 2, 2, 3};
std::multiset<int> ms2 = {10, 20, 30, 30, 40};
std::cout << "Before swap:\n";
std::cout << "ms1: ";
for (int x : ms1) std::cout << x << ' ';
std::cout << "(size = " << ms1.size() << ")\n";
std::cout << "ms2: ";
for (int x : ms2) std::cout << x << ' ';
std::cout << "(size = " << ms2.size() << ")\n\n";
// 获取指向 ms1 第一个元素的迭代器
auto it = ms1.begin(); // 指向 ms1 中的第一个元素(1)
// ---------- 执行 swap ----------
ms1.swap(ms2);
std::cout << "After swap:\n";
std::cout << "ms1: ";
for (int x : ms1) std::cout << x << ' ';
std::cout << "(size = " << ms1.size() << ")\n";
std::cout << "ms2: ";
for (int x : ms2) std::cout << x << ' ';
std::cout << "(size = " << ms2.size() << ")\n\n";
// 原先指向 ms1 的迭代器 it 现在指向的是哪个容器的元素?
// 迭代器本身依然有效,并且指向的是同一个元素(1),但该元素现在属于 ms2
std::cout << "Iterator *it = " << *it << '\n'; // 仍输出 1
// 判断它现在属于哪个容器:通过比较与容器的 begin/end
if (it != ms2.end() && *it == *ms2.begin())
std::cout << "it now belongs to ms2 (points to " << *it << " which is first in ms2)\n";
else
std::cout << "it belongs to ms1\n";
return 0;
}

emplace
在 std::multiset 中就地构造一个新元素,避免临时对象的拷贝或移动。
- 接受与元素构造函数匹配的参数包,在容器内部直接构造元素。
- 始终插入成功,不会因元素已存在而拒绝插入。
- 返回一个迭代器,指向新插入的元素。
- 插入位置由容器根据排序规则自动确定。
- 对于构造成本较高的类型,此函数可显著提升性能。
#include <iostream>
#include <set>
// 自定义类型,用于观察构造/拷贝开销
struct Product {
std::string name;
double price;
// 构造函数
Product(std::string n, double p) : name(std::move(n)), price(p) {
std::cout << " Constructor: " << name << "\n";
}
// 拷贝构造函数(输出日志)
Product(const Product& other) : name(other.name), price(other.price) {
std::cout << " Copy constructor: " << name << "\n";
}
// 移动构造函数(输出日志)
Product(Product&& other) noexcept
: name(std::move(other.name)), price(other.price) {
std::cout << " Move constructor: " << name << "\n";
}
// 用于 multiset 排序(按名称)
bool operator<(const Product& other) const {
return name < other.name;
}
};
int main() {
std::cout << "--- emplace 就地构造 ---\n";
std::multiset<Product> products;
// emplace:直接在容器内部构造 Product("Apple", 4.5)
auto it = products.emplace("Apple", 4.5);
std::cout << " Emplaced: " << it->name << " ($" << it->price << ")\n\n";
std::cout << "--- emplace 插入重复键(始终成功)---\n";
// 插入另一个 "Apple",emplace 直接构造新节点,不会失败
auto it2 = products.emplace("Apple", 3.8);
std::cout << " Emplaced duplicate: " << it2->name << " ($" << it2->price << ")\n";
std::cout << " Container size: " << products.size() << "\n\n";
std::cout << "--- insert 需要临时对象 ---\n";
// 对比 insert:需要先构造临时 Product 对象
Product tmp("Banana", 2.0); // 构造临时
products.insert(tmp); // 拷贝构造进容器
// 也可以移动临时对象
products.insert(Product("Cherry", 6.0)); // 构造临时 + 移动(或拷贝)
std::cout << "\nFinal multiset contents (sorted by name):\n";
for (const auto& p : products) {
std::cout << " " << p.name << " ($" << p.price << ")\n";
}
return 0;
}

emplace_hint
带插入位置提示的就地构造版本。
第一个参数是一个迭代器,用作插入位置的提示;后续参数为元素构造参数。
- 始终插入成功,返回指向新元素的迭代器。
- 若提示的位置非常接近实际插入点(例如恰好是应插入位置的前驱),插入操作可达到均摊常数时间复杂度;否则退化为普通插入的对数复杂度。
- 提示位置的准确性不影响函数的正确性,仅用于优化。
- 特别适合在有序批量插入时使用,可大幅减少重排查找的开销。
#include <iostream>
#include <set>
int main() {
std::multiset<int> ms = {10, 20, 30, 40, 50}; // 初始有序集合
// ---------- 准确提示:在 30 之前插入 25 ----------
// 应插入位置在 20 之后、30 之前,提示指向 30 可作为准确前驱
auto hint = ms.find(30); // 迭代器指向第一个 30
auto it = ms.emplace_hint(hint, 25); // 就地构造 25,提示准确 → 均摊常数复杂度
std::cout << "Emplaced 25 with accurate hint: " << *it << '\n';
// ---------- 不准确提示:在 begin() 位置插入 35 ----------
// 35 应位于 30 之后、40 之前,但提示位置为最小元素 10(错误提示)
auto bad_hint = ms.begin(); // 指向 10
auto it2 = ms.emplace_hint(bad_hint, 35);
std::cout << "Emplaced 35 with bad hint: " << *it2 << '\n';
// ---------- 插入重复值(始终成功)----------
auto it3 = ms.emplace_hint(ms.end(), 30); // 再插入一个 30,提示在末尾
std::cout << "Emplaced duplicate 30: " << *it3 << '\n';
// ---------- 输出最终集合 ----------
std::cout << "\nFinal multiset (sorted): ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n";
return 0;
}

2.3.查询操作
find
作用:在 std::multiset 中查找第一个与指定键等价的元素。
参数:一个键值(key)。
返回值:
- 若容器中存在该键的元素,返回指向第一个(按升序排列的第一个)键等于 key 的元素的迭代器。
- 若不存在,返回 end()。
复杂度:对数级别O(log n)。
与 std::set 的区别:
- set 中键唯一,find 返回的是该唯一元素的迭代器。
- multiset 中可能存在多个相同键,find 只返回第一个,若要访问所有匹配元素,应使用 equal_range。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含重复元素
std::multiset<int> ms = {10, 20, 20, 30, 20, 40, 30};
std::cout << "Multiset contents: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 1. 查找存在的键:返回第一个匹配元素 ----------
auto it = ms.find(20);
if (it != ms.end()) {
std::cout << "find(20) returned: " << *it << '\n'; // 20
std::cout << "This is the first element with key 20\n";
// 可以通过循环输出所有匹配元素
std::cout << "All elements with key 20: ";
auto range = ms.equal_range(20);
for (auto it2 = range.first; it2 != range.second; ++it2) {
std::cout << *it2 << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
// ---------- 2. 查找不存在的键 ----------
it = ms.find(99);
if (it == ms.end()) {
std::cout << "find(99) returned end()\n\n";
}
// ---------- 3. 对比:equal_range 返回所有匹配 ----------
auto range = ms.equal_range(30);
std::cout << "equal_range(30): from " << *range.first
<< " to " << *range.second << " (second points to 40)\n";
std::cout << "Elements with key 30: ";
for (auto it2 = range.first; it2 != range.second; ++it2)
std::cout << *it2 << ' ';
std::cout << '\n';
return 0;
}

count
作用:统计容器中与指定键等价的元素个数。
参数:一个键值(key)。
返回值:size_type 类型的整数,表示该键在容器中的出现次数(可以是 $0,1,2,\dots$)。
复杂度:对数级别($O(\log n + \text{count})$,但通常实现为 $O(\log n)$,通过 lower_bound 和 upper_bound 差值得到)。
与 std::set 的区别:
- set 的 count 返回值只能是 0或 1。
- multiset 的 count 可以返回任意非负整数,直接反映重复次数。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含重复元素
std::multiset<int> ms = {5, 10, 10, 15, 10, 20, 15, 25};
std::cout << "Multiset contents: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- count 统计各个键的出现次数 ----------
std::cout << "count(5) = " << ms.count(5) << '\n'; // 1
std::cout << "count(10) = " << ms.count(10) << '\n'; // 3
std::cout << "count(15) = " << ms.count(15) << '\n'; // 2
std::cout << "count(20) = " << ms.count(20) << '\n'; // 1
std::cout << "count(25) = " << ms.count(25) << '\n'; // 1
std::cout << "count(30) = " << ms.count(30) << '\n'; // 0(不存在)
// ---------- 典型用法:检查是否存在至少一个 ----------
int key = 10;
if (ms.count(key) > 0) {
std::cout << "\nKey " << key << " appears " << ms.count(key) << " times.\n";
}
return 0;
}

lower_bound
作用:返回指向容器中第一个不小于指定键的元素的迭代器。
参数:一个键值(key)。
返回值:
- 若存在键 >= key 的元素,返回指向其中第一个(按升序)元素的迭代器。
- 若所有元素的键都小于 key,返回 end()。
行为细节:
- 当 key 存在于容器中时,lower_bound 精确指向该键的第一个出现位置。
- 当 key 不存在时,指向第一个大于 key 的元素(即应插入位置)。
复杂度:对数级别(O(log n))。
与 std::set 的区别:set 中 lower_bound 也是指向第一个 >= key 的元素,但因其键唯一,当键存在时即指向该元素;multiset 则指向该键的第一个副本。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含重复元素
std::multiset<int> ms = {10, 20, 20, 30, 30, 30, 40};
std::cout << "Multiset contents: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 1. 键存在:返回该键的第一个出现位置 ----------
auto it = ms.lower_bound(20);
std::cout << "lower_bound(20) = " << *it << '\n'; // 20(第一个20)
// 验证确实是第一个副本
std::cout << "Elements from lower_bound(20): ";
for (auto it2 = it; it2 != ms.end() && *it2 == 20; ++it2)
std::cout << *it2 << ' ';
std::cout << "\n\n";
// ---------- 2. 键不存在(介于元素之间):返回第一个大于 key 的元素 ----------
it = ms.lower_bound(25); // 25 不在容器中,第一个 ≥25 的是 30
std::cout << "lower_bound(25) = " << *it << '\n'; // 30
it = ms.lower_bound(35); // 第一个 ≥35 的是 40
std::cout << "lower_bound(35) = " << *it << "\n\n";
// ---------- 3. 键小于所有元素:返回 begin() ----------
it = ms.lower_bound(5);
std::cout << "lower_bound(5) = " << *it << "\n\n"; // 10
// ---------- 4. 键大于所有元素:返回 end() ----------
it = ms.lower_bound(50);
if (it == ms.end())
std::cout << "lower_bound(50) = end()\n";
return 0;
}

upper_bound
作用:返回指向容器中第一个大于指定键的元素的迭代器。
参数:一个键值(key)。
返回值:
若存在键 > key 的元素,返回指向其中第一个元素的迭代器。
若不存在这样的元素,返回 end()。
行为细节:
- 当 key 存在于容器中时,upper_bound 指向该键所有元素之后的位置(即第一个大于该键的元素,或 end())。
- 它与 lower_bound 共同定义了一个左闭右开区间 [lower_bound, upper_bound),该区间包含了容器中所有键等于 key 的元素。
复杂度:对数级别(O(log n))。
与 std::set 的区别:set 中 upper_bound 指向唯一元素之后的位置;multiset 中它指向重复键区间的末尾。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含重复元素
std::multiset<int> ms = {10, 20, 20, 30, 30, 30, 40};
std::cout << "Multiset contents: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 1. 键存在:返回该键区间之后的位置 ----------
auto it = ms.upper_bound(20);
std::cout << "upper_bound(20) = " << *it << '\n'; // 30(第一个 >20 的元素)
// 与 lower_bound 配合:遍历所有键为 20 的元素
auto low = ms.lower_bound(20);
auto up = ms.upper_bound(20);
std::cout << "Elements with key 20: ";
for (auto it2 = low; it2 != up; ++it2)
std::cout << *it2 << ' '; // 20 20
std::cout << "\n\n";
// ---------- 2. 键不存在(介于元素之间):返回第一个大于 key 的元素 ----------
it = ms.upper_bound(25); // 25 不在容器中,第一个 >25 的是 30
std::cout << "upper_bound(25) = " << *it << '\n'; // 30
it = ms.upper_bound(35); // 第一个 >35 的是 40
std::cout << "upper_bound(35) = " << *it << "\n\n";
// ---------- 3. 键小于所有元素:返回第一个元素(最小元素)----------
it = ms.upper_bound(5); // 第一个 >5 的是 10
std::cout << "upper_bound(5) = " << *it << "\n\n";
// ---------- 4. 键大于等于最大元素:返回 end() ----------
it = ms.upper_bound(40); // 无元素 >40
if (it == ms.end())
std::cout << "upper_bound(40) = end()\n";
it = ms.upper_bound(50);
if (it == ms.end())
std::cout << "upper_bound(50) = end()\n";
return 0;
}

equal_range
作用:返回一个迭代器对(pair<iterator, iterator>),表示容器中所有与指定键等价的元素范围。
参数:一个键值(key)。
返回值:pair<iterator, iterator>,其中:
- first 等于 lower_bound(key)。
- second 等于 upper_bound(key)。
行为细节:
- 形成的区间 [first, second) 包含了容器中所有键等于 key 的元素,按升序排列且连续存储。
- 如果 key 不存在,则 first == second(均指向第一个大于 key 的元素或同为 end()),表示空范围。
复杂度:对数级别(通常为一次树搜索得到两个边界,优于分别调用 lower_bound 和 upper_bound)。
与 std::set 的区别:
- set 的 equal_range 范围要么为空,要么仅包含一个元素。
- multiset 的 equal_range 范围可能包含多个元素,是遍历某一键所有重复项最直接、高效的方法。
#include <iostream>
#include <set>
int main() {
// 创建一个 multiset,包含重复元素
std::multiset<int> ms = {5, 10, 10, 15, 10, 20, 15, 20, 20};
std::cout << "Multiset contents: ";
for (int x : ms) std::cout << x << ' ';
std::cout << "(size = " << ms.size() << ")\n\n";
// ---------- 1. 键存在:获取所有匹配元素 ----------
int key = 10;
auto range = ms.equal_range(key);
// range.first = lower_bound(key) -> 第一个 >=10 的元素(第一个10)
// range.second = upper_bound(key) -> 第一个 >10 的元素(15)
std::cout << "equal_range(" << key << "):\n";
std::cout << " first = " << *range.first << '\n'; // 10
std::cout << " second = " << *range.second << '\n'; // 15
std::cout << " Elements with key " << key << ": ";
for (auto it = range.first; it != range.second; ++it) {
std::cout << *it << ' '; // 输出所有 10(10 10 10)
}
std::cout << "\n\n";
// ---------- 2. 另一个存在键,但只有一个副本 ----------
key = 5;
range = ms.equal_range(key);
std::cout << "equal_range(" << key << "):\n";
std::cout << " first = " << *range.first << '\n'; // 5
std::cout << " second = " << *range.second << '\n'; // 10(第一个 >5)
std::cout << " Elements: ";
for (auto it = range.first; it != range.second; ++it)
std::cout << *it << ' '; // 仅 5
std::cout << "\n\n";
// ---------- 3. 键不存在(介于元素之间)----------
key = 12;
range = ms.equal_range(key);
// lower_bound(12) = 指向第一个 ≥12 的元素(15)
// upper_bound(12) = 也指向 15(因为 15 >12)
// 此时 range.first == range.second,范围为空
if (range.first == range.second) {
std::cout << "equal_range(" << key << "):\n";
std::cout << " first == second = " << *range.first
<< " (points to first element > " << key << ")\n";
std::cout << " range is empty\n\n";
}
// ---------- 4. 键大于所有元素 ----------
key = 30;
range = ms.equal_range(key);
if (range.first == ms.end() && range.second == ms.end()) {
std::cout << "equal_range(" << key << "): both first and second are end()\n";
}
return 0;
}

3265




被折叠的 条评论
为什么被折叠?



