std::set_intersection用于计算两个有序序列的交集,需包含<algorithm>头文件,要求输入序列已排序,可应用于vector等容器,使用时需确保输出容器有足够空间或用std::back_inserter动态插入,支持自定义比较函数,时间复杂度O(m+n)。

在C++中,std::set_intersection 是一个非常实用的算法函数,用于计算两个有序序列的交集,并将结果输出到另一个容器中。它定义在 <algorithm> 头文件中,适用于任何支持随机访问迭代器的容器,比如 std::vector、std::array 或原生数组,而不仅限于 std::set。
std::set_intersection 要求输入的两个序列都已按相同规则排序(默认升序),否则结果未定义。由于 std::set 本身是有序结构,因此天然满足条件;但若使用 vector 等容器,则需提前调用 std::sort 排序。
基本语法如下:
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first);
函数返回值是指向输出范围末尾的迭代器。
立即学习“C++免费学习笔记(深入)”;
以下是一个使用 vector 求交集的典型例子:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
std::vector<int> a = {1, 2, 3, 4, 5};
std::vector<int> b = {3, 4, 5, 6, 7};
// 确保有序(这里已经有序)
std::vector<int> result;
result.resize(std::min(a.size(), b.size())); // 预分配空间
auto it = std::set_intersection(
a.begin(), a.end(),
b.begin(), b.end(),
result.begin()
);
result.erase(it, result.end()); // 删除未使用的部分
// 输出结果
for (int x : result) {
std::cout << x << " ";
}
// 输出: 3 4 5
}
注意:输出容器必须预先分配足够空间,否则会导致未定义行为。常用方法是调用 resize(),或使用 std::back_inserter 避免手动管理大小。
如果不想预分配空间,可以结合 <iterator> 中的 std::back_inserter:
std::vector<int> result;
std::set_intersection(
a.begin(), a.end(),
b.begin(), b.end(),
std::back_inserter(result)
);
这样每次插入都会自动调用 push_back,更安全灵活。
如果数据类型不支持默认小于比较,或需要降序处理,可传入自定义比较函数:
std::set_intersection(
a.begin(), a.end(),
b.begin(), b.end(),
result.begin(),
std::greater<int>{} // 用于降序排列的数据
);
此时两个输入序列必须按 greater 规则排序。
对于自定义类型,例如:
struct Person {
int id;
std::string name;
};
// 自定义比较:按 id 升序
auto cmp = [](const Person& a, const Person& b) {
return a.id < b.id;
};
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(result),
cmp);
基本上就这些。只要保证数据有序、输出容器可写、比较逻辑一致,std::set_intersection 就能高效求出交集,时间复杂度为 O(m + n),适合处理大量数据的集合操作。
以上就是C++如何使用std::set_intersection求集合交集_C++集合操作与std::set_intersection应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号