简体   繁体   English

在C ++中通过引用传递未知大小的数组

[英]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. 我有4个排序的整数数组,我正尝试将其合并为一个巨大的排序数组。

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. 我将A和B合并在一起,这给了我另一个称为X的int数组。然后我将C和D合并了,给了我另一个称为Y的int数组。最后,我将X和Y合并在一起得到了Z,这就是最终的结果。

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 在C ++中通过引用传递数组的语法是

int (&result)[size]

note that you need to know the size at compile time. 请注意,您需要在编译时知道size This is probably not what you want to do here and I would suggest to use vector<int> . 这可能不是您要在此处执行的操作,我建议您使用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. 在这种情况下,假设数组结果的大小至少不小于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. 请注意,如果您的实现支持VLA,这将不适用于VLA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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