C++语法错误

C++ Syntax Error

本文关键字:错误 语法 C++      更新时间:2023-10-16

我收到此错误:

prog.cpp:1:5: error: expected unqualified-id before ‘[’ token

形成此代码:

int [] quick_srt(int array[], int low, int n){

请问这就是问题所在?

编辑

int [] quick_srt(int array[], int low, int n){
int lo = low;
int hi = n;
comp++;
if (lo >= n){ // lo is greater then or equal to n
    return array;
}
int mid = array[(lo + hi) / 2];  //Using mid as pivot
comp++;
while (lo < hi){ //lo is less then hi
    comp++;
    while (lo < hi && array[lo] < mid){ //lo less than hi AND array[lo] less than mid
        lo++;
        comp++;
    }
    comp++;
    while (lo < hi && array[hi] > mid) {//lo less than hi AND array[lo] greater than mid
        hi--;
        comp++;
    }
    comp++; //for if
    comp++; //for else
    if(array[lo] == array[hi]){
    break; //for duplicate items
    }
    else if (lo < hi) { // less than
        int T = array[lo];
        array[lo] = array[hi];
        array[hi] = T;
        swaps++;
    }
    comp++;
}
comp++;
if (hi < lo) { //hi is less than lo
    int T = hi;
    hi = lo;
    lo = T;
}
quick_srt(array, low, lo); //recrusie call
quick_srt(array, lo == low ? lo+1 : lo, n); //re-call, if lo = low, increment lo else pass lo and n
return array;
  }

不能从函数返回数组。 参数列表中的int array[]只是int *array的语法糖,返回值没有类似物。 如果要返回指针,则需要显式执行此操作:

int *quick_srt(int array[], int low, int n);

或者,等效地:

int *quick_srt(int *array, int low, int n);

int [] 仅对函数参数有效。我建议你这样做:

void quick_srt(std::vector<int>& array, int low)

你不需要n参数。USe 'array.size() 代替。

另一种方法是使用void quick_srt(int * array, int low)

我建议使用矢量更容易