使用set可自动去重并排序,适合有序结果;unordered_set基于哈希,效率高但无序;vector结合sort与unique适用于仅用序列容器的场景。

在C++中求两个数组的并集,目标是将两个数组中的所有不重复元素合并到一个集合中。常用的方法包括使用标准库中的set或unordered_set去重,或者结合vector与算法函数实现。以下是几种常见的实现方式。
set容器本身具有自动排序和去重的特性,适合用来求并集。
set中示例代码:
#include <iostream>
#include <set>
#include <vector>
std::set<int> unionArrays(const std::vector<int>& arr1, const std::vector<int>& arr2) {
std::set<int> result;
for (int x : arr1) result.insert(x);
for (int x : arr2) result.insert(x);
return result;
}
int main() {
std::vector<int> a = {1, 2, 3, 4};
std::vector<int> b = {3, 4, 5, 6};
std::set<int> uni = unionArrays(a, b);
for (int x : uni) {
std::cout << x << " ";
}
// 输出:1 2 3 4 5 6
return 0;
}
如果不需要结果有序,unordered_set效率更高,尤其适用于大数据量。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <iostream>
#include <unordered_set>
#include <vector>
std::vector<int> unionArraysUnordered(const std::vector<int>& arr1, const std::vector<int>& arr2) {
std::unordered_set<int> set;
for (int x : arr1) set.insert(x);
for (int x : arr2) set.insert(x);
return std::vector<int>(set.begin(), set.end());
}
若想避免使用set类,也可以用vector手动处理。
std::unique去除相邻重复元素erase使用才能真正删除示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> unionArraysUnique(std::vector<int> arr1, std::vector<int> arr2) {
std::vector<int> result;
result.insert(result.end(), arr1.begin(), arr1.end());
result.insert(result.end(), arr2.begin(), arr2.end());
std::sort(result.begin(), result.end());
auto it = std::unique(result.begin(), result.end());
result.erase(it, result.end());
return result;
}
这种方法适合对内存控制较严格或不想引入额外容器的场景。
三种方式各有适用场景:
set:需要有序结果,代码简洁unordered_set:追求性能,不要求顺序vector+unique:希望只依赖vector,避免关联容器基本上就这些常见做法,选择取决于是否需要排序、性能要求以及数据规模。
以上就是c++++中如何求两个数组的并集_c++数组并集实现方式的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号