23

I have a quicksort that I wrote here:

void swap(int& a, int& b);
int mid(int lo, int hi);

// My quicksort implementation
void sort(int vec[], int lo, int hi)
{
        int mid;
        if (hi > lo) {
                int i = lo + 1;
                int j = hi;
                int p = mid(lo, hi);
                swap(vec[lo], vec[p]);
                mid = vec[lo];
                while (i < j) {
                        if (vec[i] <= mid) {
                                i++;
                        } else {
                                while (i < --j && vec[j] >= mid);
                                swap(vec[i], vec[j]);
                        }
                }
                i++;
                swap(vec[lo], vec[i]);
                sort(vec, lo, i);
                sort(vec, j, hi);
        }
}

void swap(int& a, int& b)
{
        int temp = a;
        a = b;
        b = temp;
}

int mid(int lo, int hi)
{
        return lo + ((hi - lo) / 2);
}

I tried compiling to an object file with g++ -g -c array.cpp -o array.o I get this error:

array.cpp:24:14: error: called object type 'int' is not a function or function
    pointer
            int p = mid(lo, hi);
                    ~~~^
1 error generated.

Everything looks correct. Can anyone help me figure out what is wrong?

4

2 回答 2

34

您的局部变量mid是在更接近使用点的范围内声明的,因此它“遮蔽”了mid()函数;编译器认为您正在尝试“调用”一个无效的整数。重命名局部变量来解决这个问题:

int midpoint;
if (hi > lo) {
    int i = lo + 1;
    int j = hi;
    int p = mid(lo, hi);
    swap(vec[lo], vec[p]);
    midpoint = vec[lo];
    ...
}

注意:您也可以使用::mid(lo, hi)而不是重命名变量,但这会使程序的读者感到困惑。

于 2013-11-01T18:33:51.807 回答
3
int mid(int lo, int hi);      // here you declared mid as function and defined
                              // it later
// My quicksort implementation
void sort(int vec[], int lo, int hi)

{
int mid;                      // but here you declared mid as local variable
if (hi > lo) {                // it will shadow int mid(int lo, int hi);
        int i = lo + 1;
        int j = hi;
        int p = mid(lo, hi);  // so this is error, mid is integer not a function

您可以更改算法中的变量名称或使用范围解析运算符::mid(lo, hi)来访问mid先前在全局范围中定义的函数

于 2013-11-01T18:37:14.650 回答