我一直试图完成这项工作,但我现在陷入了困境。任何人都可以推荐最简单的方法来完成它吗?谢谢
c[i] = a[i] + b[i];
// The snippet of code I have above works fine with operator: + - / *
// a[i] = { 1, 8, 13, 15 }
// b[i] = { 3, 8, 13, 20 }
// then c[i] = { 4, 16, 26, 35 }
// But how do i find the union and intersection of both arrays?
// I want the results to look like:
// union = {1,3,8,13,15,20}
// intersection = {8,13}
答案 0 :(得分:2)
因为你要求最简单的方法。 你可以把数组的元素放到2 std :: set
中std::set<T> set1(begin(array1), end(array1));
std::set<T> set2(begin(array2), end(array2));
然后在2个新的std :: set中使用std :: set_union和std :: set_intersection。 请查看在set union和set intersection这些链接中的完成方式 因此,STL负责处理大多数逻辑和容器。
答案 1 :(得分:0)
试试这个..
//Unioin of 2 array
#include<stdio.h>
int printUnion(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
printf(" %d ", arr1[i++]);
else if(arr2[j] < arr1[i])
printf(" %d ", arr2[j++]);
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
while(i < m)
printf(" %d ", arr1[i++]);
while(j < n)
printf(" %d ", arr2[j++]);
}
int main()
{
int arr1[] = {1, 8, 13, 15};
int arr2[] = {3, 8, 13, 20};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
printUnion(arr1, arr2, m, n);
getchar();
return 0;
}
//Intersection of two array
#include<stdio.h>
int printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while(i < m && j < n)
{
if(arr1[i] < arr2[j])
i++;
else if(arr2[j] < arr1[i])
j++;
else /* if arr1[i] == arr2[j] */
{
printf(" %d ", arr2[j++]);
i++;
}
}
}
int main()
{
int arr1[] = {1, 8, 13, 15};
int arr2[] = {3, 8, 13, 20};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
printIntersection(arr1, arr2, m, n);
getchar();
return 0;
}