【问题标题】:C++ Function expects size_t parametersC++ 函数需要 size_t 参数
【发布时间】:2015-03-23 15:59:17
【问题描述】:

我正在设计一个 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

}

在main方法中

    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)’”

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

【问题讨论】:

  • 标准库中有一个std::bsearch() 函数。而且你错误地传递了你的论点。
  • int max = sizeof(array)/sizeof(array[0]); 这是错误的。试试打印吧。

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


【解决方案1】:

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

#include <cstdlib>
using namespace std;

【讨论】:

  • 这真是令人惊讶,我没想到会有一个同名的库函数。非常感谢!另外,我意识到我传入的参数类型错误,但实际上我这样做是为了安抚编译器。那么我只需要重命名方法并改回参数即可。
  • 这是一个(又一个)很好的例子,说明为什么将 using namespace std; 放在你的代码中总是是一件坏事。即使你的程序只有 3 行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 2012-10-04
  • 2021-02-26
  • 2012-11-10
  • 1970-01-01
相关资源
最近更新 更多