std::set_union要求输入序列有序,将两个有序区间合并为并集并存储到输出容器。示例中合并两vector后去重得1 2 3 5 6 7 8 9,需预分配空间并用返回迭代器调整大小。

在C++中,std::set_union 是 <algorithm> 头文件提供的一个标准算法,用于计算两个有序序列的并集。它并不会去重或排序输入序列,因此要求输入数据必须是已排序的,否则结果不可预期。
函数原型如下:
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_union(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
它将 [first1, last1) 和 [first2, last2) 两个区间中的所有元素合并成一个有序序列,保存到 result 指向的位置。相同元素只保留一份(即数学意义上的并集),前提是两个输入序列本身已按升序排列。
下面是一个使用 std::set_union 合并两个 vector 的完整例子:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> a = {1, 3, 5, 7, 9};
std::vector<int> b = {2, 3, 6, 7, 8};
std::vector<int> result;
// 预分配空间避免迭代器失效
result.resize(a.size() + b.size());
auto it = std::set_union(a.begin(), a.end(),
b.begin(), b.end(),
result.begin());
// 调整实际大小
result.resize(std::distance(result.begin(), it));
for (int x : result) {
std::cout << x << " ";
}
// 输出: 1 2 3 5 6 7 8 9
return 0;
}
使用 std::set_union 时需注意以下几点:
如果数据本身用 std::set 存储,则无需手动排序:
std::set<int> s1 = {1, 3, 5};
std::set<int> s2 = {3, 4, 5, 6};
std::vector<int> res;
res.resize(s1.size() + s2.size());
auto it = std::set_union(s1.begin(), s1.end(),
s2.begin(), s2.end(),
res.begin());
res.resize(std::distance(res.begin(), it));
基本上就这些。只要记住:有序输入、预留空间、正确处理返回迭代器,就能安全高效地求出两个集合的并集。不复杂但容易忽略细节。
以上就是C++如何使用std::set_union求集合并集_C++集合操作与std::set_union实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号