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

C++ Binary Search Issue with Array Length

出于某种原因,当您输入 "b" 或任何内容(考虑已经排序)时,下面的代码不会给出输出 "GOTCHA\n" 但是,如果我使用矢量,它工作正常!似乎如果你调试它的字符串大小 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 << "GOTCHA\n";
        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;
}

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

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

你需要这样的东西

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

希望对您有所帮助!