我已经使用指针在内存中分配了两个数组,并且我还有一个函数来获取用户的元素输入并将其存储在数组中。我唯一的问题是我不知道如何在两个数组中找到公共元素并将其存储在另一个新数组中。我该怎么做?
我已经尝试将第一个数组的每个元素与第二个数组的每个元素进行比较,如果它们彼此相等,那么我应该将其存储在新数组中。但是,这对我来说似乎不是一个有效的代码。
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? */
您当然想std::set_intersection
从<algorithm>
标题中使用它。请记住,指向连续内存的原始指针有资格作为输入迭代器,因此:
#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 在评论中指出的那样,该算法要求对两个输入序列进行排序。
如果无论如何都没有对输入范围进行排序并且您担心性能,则可能需要阅读此博客文章以获取替代方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句