[英]How can I find the union of two sorted arrays using pointers?
我创建了一个union函数来查找将要传递的两个排序数组的联合。有人可以告诉我为什么这会打印全0的数组吗?
这是我编写的整个程序:
#include <iostream>
#include <fstream>
using namespace std;
int test_array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int test2_array[] = {0, 1, 2, 3, 4, 5, 6, 7, 10, 9};
int size_1 = 10;
int size_2 = 10;
template <typename T>
T* union_func(T *P1, int size1, T*P2, int size2) {
T* result_new = new T[size1 + size2];
int i = 0, j = 0;
while(i < size1 && j < size2)
{
for(int i =0 ; i < size2; i++) {
if(*P1 == *P2){
*result_new = *P1;
*P1++;
*P2++;
} else if(*P1 > *P2) {
*result_new = *P2;
*P1++;
*P2++;
} else {
*result_new = *P1;
*P1++;
*P2++;
}
}
i++;
j++;
}
return result_new;
}
int printArray(int *ptr, int length) {
for(int i = 0; i < length; i++) {
printf("%d%s", ptr[i], " ");
}
}
int main() {
std::cout << union_func(test_array, size_1, test2_array, size_2) << std::endl;
std::cout << printArray((union_func(test_array, size_1, test2_array, size_2)), size_1) << std::endl;
}
首先是一些小问题:
size1
printArray
函数什么也不返回,最好将其返回类型更改为void
printArray
函数自己执行打印,无需将其传递给cout
关于您的代码:
*result_new
,这是组合数组的第一个元素 P1
和P2
) i++; j++;
i++; j++;
可能会使较长数组中的某些元素不被处理。 实际上,您不需要两级循环,三个单级循环就足够了:
template <typename T>
T * union_func(T * P1, int size1, T * P2, int size2, int * size3) {
T * result_new = new T[size1 + size2];
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (P1[i] < P2[j]) {
result_new[k] = P1[i];
i++;
k++;
} else if (P1[i] > P2[j]) {
result_new[k] = P2[j];
j++;
k++;
} else {
result_new[k] = P1[i];
i++;
j++;
k++;
}
}
while (i < size1) {
result_new[k++] = P1[i++];
}
while (j < size2) {
result_new[k++] = P2[j++];
}
*size3 = k;
return result_new;
}
并在您的主要功能中:
int main() {
int sorted_len;
int * sorted_arr = union_func(test_array, size_1, test2_array, size_2, &sorted_len);
printArray(sorted_arr, sorted_len);
delete sorted_arr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.