c++ - 使用 vector 进行二进制搜索

标签 c++ search vector

因此,我已经了解了二进制搜索及其工作原理,甚至在没有用户输入的情况下使用常量数组对其进行了尝试,但是现在我试图应用vector而不是array来让用户在其中输入两个列表的值。从 vector 中搜索数字以及要搜索的目标。这里我在使用数组时使用了普通的分而治之

using namespace std;
int Binary_search(int x[],int size,int target){
    int maximum= size-1;
    int minimum = 0;
    int mean;
    while (maximum>minimum){
        mean = (maximum+minimum)/2;
        if (x[mean] == target){
            cout << "The number you're looking for is found! \n";
            return mean;
        }
        else if(x[mean] > target){
            maximum = (mean-1);
        }
        else{
            minimum = (mean+1);
        }
    }
    return -1;
}
int main(){
    int x[]={1,2,3,4,5};
    int a=sizeof(x)/sizeof(x[0]);
    int target=4;
    int show=Binary_search(x,a,target);
    if (show != -1){
        cout << "Your result is in the index: " << show;
    }
    return 0;
}

我的问题是,我使用vector进行了几乎相同的方法,但是它显示了无限数量的**您的结果在索引处发现:**(错误索引数)。或者它根本不显示任何结果,甚至表明未找到结果,每次都会有所不同。这是在使用 vector 时
#include <iostream>
#include <vector>
using namespace std;
int Binary_search(vector<int>x,int target){
    int maximum=(x.size())-1;
    int minimum = 0;
    int mean;
    while (maximum>minimum){
        mean = (maximum+minimum)/2;
        if (x[mean] == target){
            cout << "The number you're looking for is found! \n";
        }
        else if(x[mean] > target){
            maximum = (mean-1);
        }
        else{
            minimum = (mean+1);
        }
    }
    return -1;
}
int main(){
    unsigned int i;
    int n;
    vector<int>x;
    cout << "Enter the amount of numbers you want to evaluate: ";
    cin >> i;
    cout << "Enter your numbers to be evaluated: " << endl;
    while (x.size() < i && cin >> n){
        x.push_back(n);
    }
    int target;
    cout << "Enter the target you want to search for in the selected array \n";
    cin >> target;
    int show = Binary_search(x,target);
    if (show == -1){
        cout << "Your result is not found ! ";
    }
    else{
        cout << "Your result is in the index: " << show;
    }
    return 0;
}

所以我认为问题出在这部分int maximum=(x.size())-1;,也许是关于如何使用 vector 的大小?有人可以启发我

最佳答案

您需要在此行之后添加return mean

cout << "The number you're looking for is found! \n";

就像在阵列版本中一样。

另外,如评论中所述,这仅在用户输入排序的数据时才有效。

关于c++ - 使用 vector 进行二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677015/

相关文章:

c++ - 经典数组与 std::array

c++ - 分配给堆

excel - 使用模式搜索和复制 move 单元格

generics - 可变借位在循环的上一迭代中从此处开始

指向文件的指针的 C++ vector

c++ - 模板化 lambda 的显式实例化

c++ - Qt父机制

javascript - PHP - 在数据库中使用一个输入进行搜索

python - 搜索 CSV 文件 (Python)

c++ - "vector subscript out of range"错误错误(VS2013)