简体   繁体   中英

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. In a way that allows me to call '.size' on the array. 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'

#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). prefer to use std::vector instead (and then you have void insertionSort(std::vector<int> &v) ).

if you cannot use std::vector , you may use:

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(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. 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.

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

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