我已经使用指针在内存中分配了两个数组,并且我还有一个函数来获取用户输入的元素并将其存储在数组中。我唯一的问题是我不知道如何在两个数组中找到公共元素并将其存储在另一个新数组中。我该怎么办?
我已经尝试过将第一个数组的每个元素与第二个数组的每个元素进行比较,如果它们彼此相等,则应该将其存储在新数组中。但是,对于我来说,这似乎并不是有效的代码。
int *j = new int[n];
getList(j, n);
int *k = new int[m];
getList(k, m);
/* how would I create a new array to
store the common elements of the
previous two arrays and display its elements? */
答案 0 :(得分:1)
您当然想使用<algorithm>
标头中的std::set_intersection
。请记住,指向连续内存的原始指针可以作为输入迭代器,因此:
#include <algorithm>
#include <vector>
std::vector<int> result;
// Make sure that [j, j + n) and [k, k + m) are sorted
std::set_intersection(j, j + n, k, k + m, std::back_inserter(result));
请注意,正如@john在评论中指出的那样,此算法要求对两个输入序列进行排序。
如果输入范围仍未排序,并且您担心性能,则可能需要阅读this blog post作为替代。