用布尔函数递归C++中的二元搜索

用布尔函数递归C++中的二元搜索,c++,pointers,recursion,C++,Pointers,Recursion,我有一个学校作业,要求我创建一个递归二进制搜索函数。我不允许更改函数签名。 我的指针经验不是最好的,我想我的问题就在那里。 我得到了一个Stackoveflow,但我真的不明白这条路 bool contains(const int* pBegin, const int* pEnd, int x) { int length = pEnd - pBegin;//gives me the length of the array const int* pMid = pBegin + (l

我有一个学校作业,要求我创建一个递归二进制搜索函数。我不允许更改函数签名。 我的指针经验不是最好的,我想我的问题就在那里。 我得到了一个Stackoveflow,但我真的不明白这条路

bool contains(const int* pBegin, const int* pEnd, int x)
{
    int length = pEnd - pBegin;//gives me the length of the array
    const int* pMid = pBegin + (length / 2);
    if(length == 1)
    {
        if(*pMid != x)
           return false;
        return true;
    }
    else if(x < *pMid)
        return contains(pBegin, pMid-1, x);
    else 
        return contains(pMid, pEnd, x);
}

void main(){
    setlocale(LC_ALL, "swedish");
    int arr[10];
    for(int i = 0; i < 10; ++i)
        arr[i] = i;
    bool find = contains(&arr[0], &arr[10], 3);//arr[10] points to the index after the array!
    cout <<"found = "<< find << endl;
    system("pause");
}

有人能解释一下我做错了什么,以及我怎样才能做得更好吗?

堆栈溢出是由于太深的递归造成的。 您的数组不太可能大到足以成为一个问题,所以您拥有的是无界递归。。。contains一直在调用自身,但检测不到这一点

看看这是如何实现的,并添加断言

您的代码假定 pEnd>pBegin

您的代码无法处理这种可能性

#include <assert.h>
bool contains( ... )
{
    assert(pBegin > pEnd);
    ...
现在,如果这个假设不正确,它将中止


pEnd>pBegin有两种可能为false,也就是说,听起来您可能需要学习如何使用调试器来逐步完成代码。有了一个好的调试器,您可以逐行执行您的程序,并查看它偏离预期的地方。这是一个必要的工具,如果你要做任何编程。进一步阅读:我得到了一个Stackoveflow——可能是由于无限递归。你正在调用包含,其中包含,调用,包含,等等,并且永远不会跳出这个调用链直到堆栈溢出。如果你使用C++,你需要摆脱使用int ARR(10)的习惯,而使用STD::向量数组。在我的机器上,这很好。@为什么?如果您知道编译时的大小,那么裸数组是可以的。我更喜欢std::array,但这不是问题。vector将需要动态分配,如果不需要,就没有理由为此付费。