【问题标题】:C++: Variable Not Affected By The Void FunctionC++:不受 Void 函数影响的变量
【发布时间】:2012-04-25 17:56:39
【问题描述】:

我已经尝试实现一个基本的快速排序算法,并且我认为我已经正确地实现了它。但是,这些函数根本不影响数组。可能是什么原因?我不知道出了什么问题,所以我决定在这里咨询我的程序员同事:

#include <iostream>
#include <vector>

using namespace std;

int partition(vector<int> A,int low,int high)
{
    int pivot=A[high-1];
    int boundryForLowerArray=low-1;
    for(int i=low;i<high-2;i++)
    {
        if(A[i]<=pivot)
        {
            boundryForLowerArray++;
            swap(A[i],A[boundryForLowerArray]);
        }
    }
    swap(pivot,A[boundryForLowerArray+1]);
    return boundryForLowerArray+1;
}
void quickSort(vector<int>A,int low,int high)
{
    if(low<high)
    {
        int q=partition(A,low,high);
        quickSort(A, low, q-1);
        quickSort(A, q+1, high);
    }
}


int main(int argc, const char * argv[])
{

    vector<int>A,sorted;
    A.push_back(2);
    A.push_back(8);
    A.push_back(7);
    A.push_back(1);
    A.push_back(3);
    A.push_back(5);
    A.push_back(6);
    A.push_back(4);
    quickSort(A, 0, A.size());
    for(int i=0;i<A.size();i++)
        cout<<A[i]<<" ";
    return 0;
}

【问题讨论】:

  • +1 获取完整的示例程序。

标签: c++ performance algorithm sorting


【解决方案1】:

您通过值而不是通过引用传递 A,因此 quickSort 正在制作 A 的副本并对其进行排序。而是尝试通过引用传递向量:

int partition(vector<int>& A,int low,int high)

...和

void quickSort(vector<int>& A,int low,int high)

【讨论】:

  • @rolandbishop 只需将他上面提到的两行更改(即vector&lt;int&gt;vector&lt;int&gt;&amp;),它就像一个魅力。
  • 我猜它确实如此,但它让我意识到我已经编写了一个不排序的快速排序算法,哈哈。
【解决方案2】:

因为您通过值而不是通过引用传递参数。实际上,您应该有一个带有迭代器的函数,用于数组的开始和结束(vec.begin(),vec.end())作为参数。此外,您的算法应该接受任何类型的迭代器。所以你应该使用模板!

template<class Iterator>
void quick_sort(Iterator begin, Iterator end) { 
   for(auto iter = begin;iter != end;iter++) 
      *iter; // access to the value of the iterator

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多