【发布时间】:2014-12-03 20:57:51
【问题描述】:
我花了一个小时试图弄清楚这一点 - 我如何编写这个函数(在代码顶部 - 插入排序),它允许我通过引用传递一个数组。以一种允许我在数组上调用“.size”的方式。它必须是这个分配的数组。
我尝试过不通过引用传递它,在调用 size 之前取消引用数组等。我不断收到错误:(。
这是此代码的最新编译器错误:
insertionSort.cpp:11: 错误:参数“A”包括对未知绑定数组“int []”的引用 insertSort.cpp:在函数‘void insertSort(int (&)[])’中: insertSort.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;
}
【问题讨论】:
-
这不是 Java。原生数组没有
size()成员。 -
如果大小在编译时没有固定,你应该使用
std::vector<> -
您不能“在阵列上调用 .size”。 C++ 中的内置数组不是类,它们没有方法。您不能“调用”阵列上的任何内容。如果您不知道数组大小,通常是不可能确定数组大小的。
-
@AndreyT 总是可以确定命名数组的大小
-
@Matt McNabb:不是真的。指向未知大小数组的指针或引用(如上例中的那个)可以正确初始化(即使它需要强制转换),然后用于合法访问某个命名数组的内容。然而,它无法让您确定该数组的实际大小。
标签: c++ arrays pass-by-reference variable-length-array