我正在设计一个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)'”
附加三个参数是什么?我没有在方法中定义它们,为什么它要我提供它们呢?该方法是否试图比较这两个参数?
答案 0 :(得分:4)
bsearch(&searchArray, &target)
与bsearch(int[], int key)
的签名不符。但是,前两个参数确实匹配std::bsearch
的签名,您可能通过以下方式将其引入命名空间:
#include <cstdlib>
using namespace std;