C++数组长度的二进制搜索问题

C++ Binary Search Issue with Array Length

本文关键字:二进制 搜索 问题 数组 C++      更新时间:2023-10-16
当您

输入"b"或任何东西(考虑已经排序(时,由于某种原因,下面的代码不会给出输出"GOTCHA",但是如果我使用矢量,它可以正常工作! 似乎如果你调试它字符串大小 x->length((-1; 不给出数组的长度,而是给出 0 作为最大长度 解决方案是什么?

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string x[] = { "a", "b", "c", "d" };
string s;
cin >> s;
int max = x->size()-1;
int min = 0;
int middle = (max + min) / 2;
while (min <= max) //BinarySearch Begins
{
    middle = (max + min) / 2;
    if (s == x[middle]) //if found display message
    {
        cout << "GOTCHAn";
        break;
    }
    else if (s > x[middle])//if actual string is after first guess increase
        min = middle + 1;
    else max = middle - 1; //else decrease
 }
 system("pause");
 return 0;
}

你需要这样的东西

int max = sizeof(x)/sizeof(x[0]) - 1;

希望这有帮助!

在下面的代码中,"x"是一个C风格的数组,你应该使用sizeof(x(来返回它的大小。 x->length(( 或 x->size(( 不正确。

   int max = x->size()-1;