【发布时间】:2014-05-05 07:11:14
【问题描述】:
我正在尝试编写一个包含数字数组的类,您可以使用函数 myArray.quicksort() 对其进行排序。 在创建 Array 的新对象时,我将长度传递给构造函数,然后填充它:
public: int Items[];
/*-- Constructor --*/
Array(int n){
length = n;
for(int i=0; i<length; i++){
int zahl;
Items[length];
cout << "Item" << i << ": ";
cin >> number;
Items[i] = number;
}
...
在创建 Array 之后,这个打印出来的函数就可以正常工作了:
void Array::show(){
for(int i=0; i<this->length; i++){
cout << this->Items[i] << " ";
}
}
但是在我尝试对其进行排序后,它会打印出废话:
void Array::quickSort(int left, int right){
int i=left, j=right;
int tmp;
int pivot = this->Items[(left + right) / 2];
while(i <= j){
while (this->Items[i] > pivot)
i++;
while (this->Items[j] < pivot)
j--;
if (i <= j) {
tmp = this->Items[i];
this->Items[i] = this->Items[j];
this->Items[j] = tmp;
i++;
j--;
}
};
if (left < j)
quickSort(left, j);
if (i < right)
quickSort(i, right);
}
我确定我完全混淆了数组指针。
但我似乎无法找到解决方案。
这里最大的缺陷在哪里?
【问题讨论】:
-
如果你想实现你自己的数组,你不能有数组,你必须使用指针并动态分配(
new[])内存。不要忘记delete[]内存,也可以阅读the rule of three。请记住:虽然数组和指针通常可以互换使用,但数组和指针仍然不同,需要以不同方式声明(即您不能拥有int arr[]并使用new[]为其分配内存)。
标签: c++ arrays pointers object quicksort