【问题标题】:Modular Quicksort Implementation (C++)模块化快速排序实现 (C++)
【发布时间】: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


【解决方案1】:

标准 C++ 没有flexible array members(就像 C99 一样)。

您不需要 Array 类,而是使用 std::vector&lt;int&gt;(或者如果数组长度是编译时间常数,则可能使用 std::array 和 C++11)

如果要声明包含ItemsArray 类,请按照Joachim Pileborg 评论中的提示,了解rule of three(在C++11 中,它变成了五规则),所以声明:

int *Items;

在你的类中,然后用

初始化它
Items = new int[n];

在其构造函数[s]中,并用

销毁它
delete [] Items;

在你的析构函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 2017-02-18
    • 2017-05-09
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多