[英]Passing unknown Array to Function by reference (C++)
我花了一個好小時試圖弄清楚這一點-如何編寫此函數(在代碼頂部-insertSort),該函數允許我通過對其進行引用來傳遞數組。 以一種允許我在數組上調用'.size'的方式。 該分配必須是一個數組。
我試圖不通過引用傳遞它,在調用它的大小之前先對數組進行解引用,等等。我一直在遇到錯誤:(。
這是此代碼的最新編譯器錯誤:
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;
}
當您這樣做時:
std::cin >> Asize;
int A[Asize]; // Not standard
您可以使用編譯器的擴展名來使用VLA(可變長度數組)。 寧願使用std::vector
代替(然后您將具有void insertionSort(std::vector<int> &v)
)。
如果您不能使用std::vector
,則可以使用:
std::unique_ptr<int[]> A(new int [Asize]);
由於只有在運行時才知道大小,因此必須將大小傳遞給函數:
void insertionSort(int* a, std::size_t size)
並按以下方式調用insertionSort
:
insertionSort(A.get(), ASize);
利用已知的數組編譯時間大小,
void insertionSort(int (&A)[42])
是通過引用傳遞數組的正確方法。
重要的是要記住,C數組只是指向數組第一個元素的指針。 傳遞數組很容易,您只需執行以下操作:
void foo(int *array)
要么
void foo(int array[])
但是,由於它只是指向其基本類型的指針,因此沒有要調用的成員函數,也沒有任何線索可以了解超出其范圍的內存結構(即,沒有長度概念)。 如果您想知道傳遞的動態數組的長度,則需要將長度作為第二個參數傳遞,大概是創建該數組的任何人都應該知道其長度。
void foo(int *array, unsigned int length)
或者,您可以避免所有這些情況,並使用概念上類似於Java中的ArrayList的向量。
數組可以通過引用傳遞,例如:
void somefunc(int (&arr)[30]) {}
這將確保您不能為此數組傳遞任何其他大小(固定大小的數組):因此,您不能這樣做:
int a[40];
func(a); // compilation error
但是,任意大小的數組也可以通過引用傳遞,例如:
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
}
因此,更正的功能如下:
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.