c++ - 从 2 个单独的数组中删除重复元素

标签 c++ arrays subtraction

我将如何从 2 个数组中减去元素?

我的 array_1[5] 数组包含元素 {1, 2, 3, 4, 5}array_2[3]包含元素 {2, 3, 5}。在数学课上,我认为我只需要用 {1, 4} 减去要留下的组。我试过像整数一样减去数组,但我不知道如何正确使用索引。我也试过对第二个数组进行排序,然后检查它们的索引是否相等,但这不起作用。

我怎样才能用 C++ 完成这项工作?

最佳答案

您正在寻找两个集合之间的差异,即 standard algorithms 中的一个。

#include <algorithm>
#include <vector>
#include <iterator>

int array_1[] = { 1, 2, 3, 4, 5 };
int array_2[] = { 2, 3, 5 };

std::vector<int> difference;

std::set_difference(std::begin(array_1), std::end(array_1), std::begin(array_2), std::end(array_2), std::back_inserter(difference));

// difference now contains { 1, 4 }

根据您的意见,我建议您将数组作为 std::vectors。然后它变得更简单。

std::vector<int> array_1 = { 1, 2, 3, 4, 5 };
std::vector<int> array_2 = { 2, 3, 5 };

std::set_difference(array_1.begin(), array_1.end(), array_2.begin(), array_2.end(), std::back_inserter(difference));

关于c++ - 从 2 个单独的数组中删除重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755130/

相关文章:

c++ - 双自由或腐败(出) - C++

r - 减去行并创建新的行名称

Python - 在列中打印二维数组

Python numpy 减法没有负数(4-6 得到 254)

r - 如何从R中的列中的每一行中删除前三个字符

c++ - 从两个多态类继承

C++ AMP 嵌套循环

c++ - 重载 `To to = from;` 和 `To to = {from};` 中的转换构造函数和转换运算符

arrays - Perl6 : Pushing an array to an array of arrays with one element seems not to work as expected

java - 将 long[] 更改为 Set。错误消息 : The method addAll in the type Collections is not applicable for the arguments (Set<Long>, 长[])