未在此范围内声明的函数

Function not declared in this scope?

本文关键字:函数 声明 范围内      更新时间:2023-10-16

这是我的代码。它告诉我当我在 kSmall 中调用它时没有声明分区......有什么想法吗?

int kSmall(int A[], int k, int low, int high){
    int pivot = A[(low+high)/2];
    int idx = partition(A, pivot, low, high);
    if(idx-low+1>k)
        kSmall(A,k,low,idx-1);
    else if(idx-low+1<k)
        kSmall(A,k,idx+1,high);
    else
        return A[idx];
}
int partition(int A[], int p, int low, int high){
    int temp;
    int left = low;
    int right = high;
    while (left < right){
        while (A[left]<p)
            left++;
        while (A[right]>p)
            right--;
        if (left<right){
            temp = A[left];
            A[left] = A[right];
            A[right] = temp;
            }
    }
    return left;
}

确切的错误是:main.cpp:36:43:错误:未在此范围内声明"partFunc"

如果您在 cpp 文件 main 中的 kSmall() 之前定义 partition(.cpp 问题将得到解决。

您必须在

调用函数的函数之前声明函数partition()

只需添加此行:

int partition(int[], int, int , int );

kSmall之前.这是因为 kSmall() 调用 partition(),它给出了一个错误,因为它之前没有 partition() 函数,所以你可以在它之前定义函数,或者简单地提供一个原型。