C++ 中的数组索引从 0 开始。
还有这个说法
cout << arr3[10] << endl;
不输出数组。它尝试输出数组索引为 10 的不存在元素。
并且循环无效,因为它试图访问数组 arr1 和 arr2 之外的内存。
您的程序可以如下所示。
#include <iostream>
using namespace std;
int main()
{
const size_t N = 5;
int arr1[N] = { 1,3,5,7,9 }, arr2[N] = { 0,2,4,6,8 }, arr3[2 * N];
for ( size_t i = 0, j = 0, k = 0; i < 2 * N; i++)
{
if ( arr2[k] < arr1[j])
arr3[i] = arr2[k++];
else
arr3[i] = arr1[j++];
}
for ( const auto &item : arr3 ) cout << item << ' ';
cout << '\n';
return 0;
}
std::merge使用标头中声明的标准算法可以执行相同的任务<algorithm>。
例如
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
int a1[] = { 1, 3, 5, 7, 9 };
int a2[] = { 0, 2, 4, 6, 8 };
int a3[sizeof( a1 ) / sizeof( *a1 ) + sizeof( a2 ) / sizeof( *a2 )];
std::merge( std::begin( a1 ), std::end( a1 ),
std::begin( a2 ), std::end( a2 ),
std::begin( a3 ) );
for ( const auto &item : a3 ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
程序输出与上图相同。
0 1 2 3 4 5 6 7 8 9