I have 4 sorted integer arrays, which i'm trying to merge into one huge sorted array.
I merge A and B together which gives me another int array called X Then I merge C and D together which gives me another int array called Y Finally i merge X and Y together to get Z, which is the final product.
The merge function is doing exactly the same each time, just storing the results into a different array which i want to pass in by reference.
I want to do something like this:
void mergeSort(int arr1[], int arr2, int &result[]){
...
}
But i get the error "Array of reference is not allowed". What is the best way to do this?
The syntax to pass an array by reference in C++ is
int (&result)[size]
note that you need to know the size at compile time. This is probably not what you want to do here and I would suggest to use vector<int>.
You can not write such a way the function because arrays even if they have elements of the same type but with different sizes are different types.
You need to write a template function
For example
template <size_t N1, size_t N2>
void mergeSort( int ( &arr1 )[N1], int ( &arr2 )[N2], int ( &result )[N1+N2])
{
...
}
Otherwise you need to pass to the function sizes of the arrays. For example
void mergeSort( int arr1[], size_t n1, int arr2[], size_t n2, int result[])
{
...
}
In this case it is assumed that the size of array result at least is not less than n1 + n2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With