首页 > 解决方案 > 从 2 个单独的数组中删除重复元素

问题描述

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

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

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

标签: c++arrayssubtraction

解决方案


您正在寻找两组之间的差异,这是标准算法之一

#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));

推荐阅读