我需要帮助查找元素在按升序排列的排序列表中出现的次数。
我设置了以下代码,但在最后一行代码的“预期参数声明符”末尾出现错误。还说我没有以前的 binarySearch 函数原型(prototype)。这到底是什么意思?我查了一下,一开始就声明了 int binarySearch 但我没有运气。我真的不知道为什么这段代码没有运行,我花了过去两个小时调试。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//sort then search
int binarySearch(int arr[], int value, int left, int right) {
while (left <= right) {
int middle = (left + right) / 2;
if (arr[middle] == value)
return middle;
else if (arr[middle] > value)
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
int main()
{
int a[] = {12,3,4,4,4,5,6,7};
int num;
num = sizeof(a)/sizeof(int);
for(int i=0; i<num; i++)
cout<<a[i]<<" ";
cout<<endl;
int value;
cout<<"Enter a value you want to find in the array."<<endl;
cin>>value;
cout<<"The element is at "<<int binarySearch(int a[], value, 0, int num);
}
最佳答案
这不是调用函数的方式。您不能只复制函数定义行并替换一两个参数。将该行替换为:
cout<<"The element is at "<<binarySearch(a, value, 0, num);
注意:这不会解决算法本身的任何问题,只会解决调用它的问题。
关于c++ - 查找数组中的元素和出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10770854/