帮我写在C++中把多个一维数组合并为一个一维数组的代码
时间: 2023-06-09 13:07:18 浏览: 77
好的,以下是可以将多个一维数组合并为一个一维数组的C代码:
```
#include <stdio.h>
void mergeArrays(int arr1[], int size1, int arr2[], int size2, int mergedArr[]) {
int i = 0, j = 0, k = 0;
// Merge elements of two arrays into one array
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
mergedArr[k++] = arr1[i++];
}
else {
mergedArr[k++] = arr2[j++];
}
}
// Copy remaining elements of arr1[] if any
while (i < size1) {
mergedArr[k++] = arr1[i++];
}
// Copy remaining elements of arr2[] if any
while (j < size2) {
mergedArr[k++] = arr2[j++];
}
}
int main() {
// Define two arrays to be merged
int arr1[] = { 1, 2, 3, 4 };
int arr2[] = { 5, 6, 7, 8 };
// Determine the size of each array
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
// Determine size of merged array
int mergedSize = size1 + size2;
// Define merged array
int mergedArr[mergedSize];
// Merge two arrays
mergeArrays(arr1, size1, arr2, size2, mergedArr);
// Print the merged array
for (int i = 0; i < mergedSize; i++) {
printf("%d ", mergedArr[i]);
}
return 0;
}
```
希望能对您有所帮助。
阅读全文