1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <ciso646>
#include <iostream>
using namespace std;
// Here is a very pretty version of the function to get your (compile time) array size.
// (You can find the Standard Library equivalent in <type_traits>, but it’s ugly.)
//
// Notice the template meta-magic to get the unnamed argument array’s size.
//
// This replaces the "sizeof(arr) / sizeof(arr[0])" trick, BTW.
//
template <typename T, size_t N>
constexpr size_t array_size( const T (&)[ N ] )
{
return N;
}
// To combine the (extant) arrays, you can use the same kind of magic to
// handle their sizes.
//
template <typename T, size_t N1, size_t N2, size_t N>
void merge_arrays( const T (&arr1)[ N1 ], const T (&arr2)[ N2 ], T (&result)[ N ] )
{
// First, a sanity check (performed at compile time), just to make sure that
// you didn't goof and give a too-small array to the function.
static_assert( (N1 + N2) <= N );
// I am unsure what you mean by "merge" the arrays.
// In CS parlance, merging typically means a sorted-to-sorted combine:
size_t n = 0, n1 = 0, n2 = 0;
while ((n1 < N1) and (n2 < N2))
{
if (arr1[n1] < arr2[n2]) result[n++] = arr1[n1++];
else result[n++] = arr2[n2++];
}
while (n1 < N1) result[n++] = arr1[n1++];
while (n2 < N2) result[n++] = arr2[n2++];
}
int main()
{
// The initial arrays...
int arr1[] = { 1,2,7,9 }; //{ 7,2,9,1 }; // Since "merge" means input is sorted...
int arr2[] = { 0,1,3,4,5,8 }; //{ 8,1,5,3,4,0 }; // ...the input must therefore be sorted
// Declare our new array with a concrete size
// -- which we get from the above two arrays’ sizes
int arr3[ array_size( arr1 ) + array_size( arr2 ) ];
// Runtime merge of the array content
merge_arrays( arr1, arr2, arr3 );
// Print the results for the user
for (auto x : arr3)
cout << ' ' << x;
cout << '\n';
}
|