简体   繁体   中英

Passing an array of unknown size by reference in c++

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.

void mergeSort( int *arr1, int *arr2, int sizeOfArray, int *result[] )
{
...
}

I think the answers above give you what is likely a better solution than what you are doing. But if you absolutely insist on taking arrays (by reference and want to leave the size "unspecified"), do the following:

template <unsigned int SIZE> void mergeSort(int arr1[], int arr2, int (&result)[SIZE]){
}

Then you can pass any size arrays to it and the template argument deduction process will figure out the size at compile time. Please note that this will not work with VLA's if your implementation supports VLA's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM