C++ 函数需要 size_t 参数

标签 c++ arrays parameters binary-search size-t

我正在设计一个 C++ 二进制搜索方法,它接受一个包含 10 个整数的数组和一个要搜索的整数。我将 main 方法设计为从命令行参数获取数组并提示用户输入要搜索的整数。两者的地址都传递给 bsearch 方法(因为直接传递它们似乎不起作用),然后循环遍历数组并搜索提供的目标。我的 bsearch 方法的代码发布在下面:

void bsearch(int array[10], int key)        {
    int candidate;
    int min = 0;
    int max = sizeof(array)/sizeof(array[0]);
    bool found = false;

    while(!found)   {       //Begin iterative loop
            if(max<min)
                    break; //cout << key << " not found" << endl;   //Only executes after searching entire array
            for(int i=min;i<max;i++)        {
                    cout << array[i] << " ";        //Prints out current 
            }                                       //section being searched
            cout << endl;
            candidate = array[(max+min)/2];         //Check middle element
            if(candidate == key)    {
                    found = true;                   //Target located
            }
            else if(candidate>key)  {
                    max = ((max+min)/2)-1;          //Search lower portion
            }
            else if(candidate<key)  {
                    min = ((max+min)/2)+1;          //Search upper portion
            }
    }
    if(found)
            cout << key << " found at index " << (max+min)/2 << endl;       //Report target location
    else
            cout << key << " not found" << endl;    //Report target not found

}

在主要方法中

    int target;
    int searchArray[10];
    for(int i=0;i<10;i++)   {
            searchArray[i] = atoi(argv[i+1]);
    }
    cout << "Enter search query(one integer): ";
    cin >> target;
    bsearch(&searchArray, &target); //Problem is here

问题是,每当我尝试编译这段代码时,我都会收到错误消息:“函数‘void* bsearch(const void*, const void*, size_t, size_t, __compar_fn_t)’ 的参数太少”

额外的三个参数有什么用?我没有在方法中定义它们,为什么要我提供它们?该方法是在尝试比较两个参数还是什么?

最佳答案

bsearch(&searchArray, &target) 与您的 bsearch(int[], int key) 的签名不匹配。然而,前两个参数与 std::bsearch 的签名匹配。 ,您很可能无意中通过以下方式将其引入了命名空间:

#include <cstdlib>
using namespace std;

关于C++ 函数需要 size_t 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129794/

相关文章:

C++:从文件中分隔名字和姓氏,用逗号分隔

c++ - 从 Objective-c 委托(delegate)给 c (或者更好地称之为 : Creating listener from C to OBJ-C)

java - 我不能在数组上使用方法 setter setMarcaCelular

c - 仅获取 C 中数组的所有其他值

mysql - mysql存储过程中真的有必要指定out参数吗?

windows - 在 Windows 命令行中使用批处理文件中的参数

java - 方法不适用于参数

c++ - OpenMP 原子内存顺序

c++ - 如何对字符串进行冒泡排序?

php - 数组php中的重复总和