c++ - 查找数组中的元素和出现的次数

标签 c++ search

我需要帮助查找元素在按升序排列的排序列表中出现的次数。

我设置了以下代码,但在最后一行代码的“预期参数声明符”末尾出现错误。还说我没有以前的 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/

相关文章:

c++ - std::optional 的 const_cast 等价物

search - Solr 过滤器查询,包括 NOT 和 OR

python - Python 列表中的分层搜索

android - 在操作栏中获取搜索 View 的下拉列表

java - 如何用Java搜索最高值

c++ - OpenCV VideoCapture::get(CV_CAP_PROP_POS_MSEC) 返回 0

c++ - Makefile:根据 CC/CXX/FC 值更改编译器标志

c++ - 对称的Lerp和编译器优化

c++ - 如果系统内存足够,C++ 字符串是否可以包含无限数量的字符,并且 size_t 可以表示如此极端的长度吗?

database - Arduino 从 SD 卡读取数据库文件