【问题标题】:C++ Quicksort with vectors带有向量的 C++ 快速排序
【发布时间】:2018-05-03 02:32:45
【问题描述】:

快速排序功能工作得非常好,因为我尝试过使用标准数组。然而,当使用向量时,我收到一条错误消息,指出交换函数不接受 3 个参数。任何帮助,将不胜感激。

void quicksort(vector<int> &vec, int L, int R) {
    int i, j, mid, piv;
    i = L;
    j = R;
    mid = L + (R - L) / 2;
    piv = vec[mid];

    while (i<R || j>L) {
        while (vec[i] < piv)
            i++;
        while (vec[j] > piv)
            j--;

        if (i <= j) {
            swap(vec, i, j); //error=swap function doesnt take 3 arguments
                i++;
                j--;
        }
        else {
            if (i < R)
                quicksort(vec, i, R);
            if (j > L)
                quicksort(vec, L, j);
            return;
        }
    }
}

void swap(vector<int> v, int x, int y) { 
    int temp = v[x];
    v[x] = v[y];
    v[y] = temp;

}

int main() {
    vector<int> vec1;
    const int count = 10;

    for (int i = 0; i < count; i++) {
        vec1.push_back(1 + rand() % 100);
    }
    quicksort(vec1, 0, count - 1);

}

【问题讨论】:

  • 你是说我应该使用偏移表示法而不是下标表示法?
  • 您在声明之前尝试使用您的交换功能。编译器还没有看到它。相反,它从标准库中查看std::swap,它只需要两个参数。您需要在尝试使用函数之前声明它们。
  • 使用命名空间标准;将 std 交换函数引入您的命名空间,并将在您使用自己的交换之前声明和定义。将您的交换定义向上移动并修复应该通过引用而不是通过值(副本)获取向量的错误。
  • using namespace std;,当然是不好的做法,但在这里没有错。 std::swap 即使没有它也会被 ADL 捕获。
  • 所以基本上,我不得不将交换函数放在快速排序函数之上。现在它正在工作。谢谢你们的帮助。

标签: c++ vector pass-by-reference quicksort


【解决方案1】:

就像各种评论所说,问题是您的交换版本与 std::swap 混淆了。您可以通过在使用前移动 swap 的实现或在使用前添加声明来修复它。

同样根据 Devin 的回答,通过引用传递,以便您取回交换后的值。

这里是固定代码:

#include <vector>
using namespace std;
void swap(vector<int>& v, int x, int y);

void quicksort(vector<int> &vec, int L, int R) {
    int i, j, mid, piv;
    i = L;
    j = R;
    mid = L + (R - L) / 2;
    piv = vec[mid];

    while (i<R || j>L) {
        while (vec[i] < piv)
            i++;
        while (vec[j] > piv)
            j--;

        if (i <= j) {
            swap(vec, i, j); //error=swap function doesnt take 3 arguments
            i++;
            j--;
        }
        else {
            if (i < R)
                quicksort(vec, i, R);
            if (j > L)
                quicksort(vec, L, j);
            return;
        }
    }
}

void swap(vector<int>& v, int x, int y) {
    int temp = v[x];
    v[x] = v[y];
    v[y] = temp;

}

int main() {
    vector<int> vec1;
    const int count = 10;

    for (int i = 0; i < count; i++) {
        vec1.push_back(1 + rand() % 100);
    }
    quicksort(vec1, 0, count - 1);

}

【讨论】:

    【解决方案2】:

    void quicksort(vector<int> &vec, int L, int R) 
    

    void swap(vector<int> v, int x, int y) 
    

    第一个参数不使用引用。

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 1970-01-01
      • 2017-05-25
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多