简体   繁体   English

通过引用将未知数组传递给函数(C ++)

[英]Passing unknown Array to Function by reference (C++)

I have spent a good hour trying to figure this out - how do I write this function (at top of code - insertionSort) that allows me to pass an array by reference to it. 我花了一个好小时试图弄清楚这一点-如何编写此函数(在代码顶部-insertSort),该函数允许我通过对其进行引用来传递数组。 In a way that allows me to call '.size' on the array. 以一种允许我在数组上调用'.size'的方式。 It has to be an array for this assignment. 该分配必须是一个数组。

I have tried not passing it by reference, dereferencing the array before calling size on it, etc. I keep getting errors :(. 我试图不通过引用传递它,在调用它的大小之前先对数组进行解引用,等等。我一直在遇到错误:(。

This is the most recent compiler error for this code: 这是此代码的最新编译器错误:

insertionSort.cpp:11: error: parameter 'A' includes reference to array of unknown bound 'int []' insertionSort.cpp: In function 'void insertionSort(int (&)[])': insertionSort.cpp:13: error: request for member 'size' in ' (int )A', which is of non-class type 'int' insertSort.cpp:11:错误: 参数“ A”包括对未知绑定“ int []”数组的引用 insertingSort.cpp:在函数“ void insertSort(int(&)[])”中:insertingSort.cpp:13:错误: 请求“ (int )A”中的成员“ size”,该成员是非类类型“ int”

#include <iostream>
//#include <array> - says no such file or directory

using namespace std;


void insertionSort(int (&A)[])                 <-----ERROR HERE
{
    for (int j=1; j <= A->size(); j++)         <-----ERROR HERE
    {
        int key = A[j];
        //now insert A[j] into the sorted sequence a[0...j-1].
        int i = j-1;
        while (i >= 0 && A[i] > key)
        {
            A[i+1] = A[i];
            i -= 1;
        }
        A[i+1] = key;
    }
}

int main()
{
    int Asize = 0;

    cout << "Hello. \nPlease enter a number value for the insertionSort Array size and then hit enter: " << endl;
    cin >> Asize;

    int A[Asize];

    char Atype;

    cout << "There are three ways to order your inserstionSort array; \nb - for best case \nw - for worst case \na - for average case" << endl << "Which type do you desire for this array? \nPlease enter 'b', 'w', or 'a': " << endl;
    cin >> Atype;

    if (Atype == 'b')
    {
        cout << "You have chosen type b." << endl;
    }

    else if (Atype == 'w')
    {
        cout << "You have chosen type w." << endl;
    }

    else if (Atype == 'a')
    {
        cout << "You have chosen type a." << endl;
    }


    cout << "Terminate Program" << endl;
}

When you do: 当您这样做时:

std::cin >> Asize;
int A[Asize]; // Not standard

You use extension of your compiler to use VLA (Variable length array). 您可以使用编译器的扩展名来使用VLA(可变长度数组)。 prefer to use std::vector instead (and then you have void insertionSort(std::vector<int> &v) ). 宁愿使用std::vector代替(然后您将具有void insertionSort(std::vector<int> &v) )。

if you cannot use std::vector , you may use: 如果您不能使用std::vector ,则可以使用:

std::unique_ptr<int[]> A(new int [Asize]);

As the size is known only at runtime, you have to pass the size to your function: 由于只有在运行时才知道大小,因此必须将大小传递给函数:

void insertionSort(int* a, std::size_t size)

and call insertionSort as follow: 并按以下方式调用insertionSort

insertionSort(A.get(), ASize);

With a known compile time size of array, 利用已知的数组编译时间大小,

void insertionSort(int (&A)[42])

is the right way to pass array by reference. 是通过引用传递数组的正确方法。

It's important to remember that C array's are just pointers to the first element of the array. 重要的是要记住,C数组只是指向数组第一个元素的指针。 Passing the array is easy, you would just do something like: 传递数组很容易,您只需执行以下操作:

void foo(int *array)

or 要么

void foo(int array[])

However, since it's just a pointer to it's base type it has no member functions to call and it has no clue what the memory structure looks like beyond it (ie. has no concept of length). 但是,由于它只是指向其基本类型的指针,因此没有要调用的成员函数,也没有任何线索可以了解超出其范围的内存结构(即,没有长度概念)。 If you wanted to know the length of a dynamic array that was passed then you need to pass the length as a second parameter, presumably whatever created the array should know its length. 如果您想知道传递的动态数组的长度,则需要将长度作为第二个参数传递,大概是创建该数组的任何人都应该知道其长度。

void foo(int *array, unsigned int length)

Or, you can avoid all of this and use vectors which are conceptually similar to an ArrayList in java. 或者,您可以避免所有这些情况,并使用概念上类似于Java中的ArrayList的向量。

Arrays can be passed by reference, for example: 数组可以通过引用传递,例如:

void somefunc(int (&arr)[30]) {}

This will ensure that you cannot pass any other size for this array (fixed size array): So, you cannot do this: 这将确保您不能为此数组传递任何其他大小(固定大小的数组):因此,您不能这样做:

int a[40];
func(a); // compilation error

However, arbitrary sized array is also possible to pass by reference, for example: 但是,任意大小的数组也可以通过引用传递,例如:

template<typename T, size_t N>
void somefunc2(T (&arr)[N])
{
    // N can be used as size, as required, instead of querying size of the array
}

So, corrected function is as below: 因此,更正的功能如下:

template<typename T, size_t N>
    void insertionSort(T (&A)[N]) // ok, now
    {
        for (size_t j=1; j < N; j++) 
        {
            int key = A[j];
            //now insert A[j] into the sorted sequence a[0...j-1].
            int i = j-1;
            while (i >= 0 && A[i] > key)
            {
                A[i+1] = A[i];
                i -= 1;
            }
            A[i+1] = key;
        }
    }

尝试使用应该在Borland C ++ Builder中起作用的Array.length

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

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