You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的QuickSort无法正确排序vector<string>?求调试指导

问题根源与修改方案

你的快速排序代码无效的核心原因是函数参数使用了值传递而非引用传递,导致所有排序操作都只作用于原vector的副本,原数组根本没被修改。

需要修改的两个关键位置:

  • 将Partition1函数的vector参数改为引用:
    int Partition1(vector<string> &array, int low, int high)
    
  • 将sort函数的vector参数改为引用:
    void sort(vector<string> &array, int first, int last)
    

修改后的完整代码:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

int Partition1(vector<string> &array, int low, int high){ //for lastName sort
    string pivot = array[high]; //pivot element
    int i = (low-1); //index of smaller element
    for(int j = low; j <= high-1; j++){ //loop from low to high
        //if current iteration is less than pivot, increment low AND swap elements at i and j
        if(array[j] < pivot){
            i++; //increment index of smaller element
            swap(array[i], array[j]);
        }
    }
    swap(array[i+1], array[high]);
    return (i+1);
}

void sort(vector<string> &array, int first, int last){
    if(first < last){
        //partition array
        int pivot = Partition1(array, first, last);
        sort(array, first, pivot-1);
        sort(array, pivot+1, last);
    }
}

void swap(string &input1, string &input2) {
    string temp; //temp student object to hold info
    temp = input1;
    input1 = input2;
    input2 = temp;
}

int main(){
    vector<string> array = {"Eric", "Bob", "George", "Fred"};
    sort(array, 0, array.size()-1);
    for(int i = 0; i < array.size(); i++){
        cout << array[i] << endl;
    }
}

补充说明:

当你用值传递vector<string> array时,每次调用函数都会复制整个vector。函数内部对这个拷贝的修改不会同步到原数组,所以main函数里的vector始终保持初始状态。改用引用传递后,函数直接操作原vector的内存空间,排序的修改才能真正生效。

另外,你自定义的swap函数是正确的(使用了引用参数),不过其实可以直接使用标准库的std::swap,效果完全一致。

内容的提问来源于stack exchange,提问作者rren_nn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:20:33