【发布时间】: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