简体   繁体   English

字符串向量二分查找

[英]String vector binary search

I am trying to find a user input word inside a string vector using binary search.我正在尝试使用二进制搜索在字符串向量中查找用户输入的单词。 But it always returns a positive integer. The vector is sorted and read from a txt file.但它总是返回一个正数 integer。向量被排序并从一个 txt 文件中读取。 The file looks like.该文件看起来像。

aah
aal
aas

and so on.等等。

    int binarySearchString(vector<string> arr, string x, int n) {
    int lower = 0;
    int upper = n - 1;
    while (lower <= upper) {
    int mid = lower + (upper - lower) / 2;
    int res;
    if (x == (arr[mid]))
     res = 0;
    if (res == 0)
     return mid;
    if (x > (arr[mid]))
      lower = mid + 1;
    else
     upper = mid - 1;
    }
    return -1;
    }

As it is, unless x == (arr[mid]) is true, this code should throw a runtime exception because res will be used in the next if statement before it's been initialized.实际上,除非x == (arr[mid])为真,否则此代码应抛出运行时异常,因为res将在初始化之前用于下一个 if 语句。 When I initialize res to some negative value, the function seems to work.当我将res初始化为某个负值时,function 似乎可以工作。

int binarySearchString(vector<string> arr, string x, int n) {
    int lower = 0;
    int upper = n - 1;
    while (lower <= upper) {
        int mid = lower + (upper - lower) / 2;
        int res = -2;

        if (x == (arr[mid]))
            res = 0;

        if (res == 0)
            return mid;

        if (x > (arr[mid]))
            lower = mid + 1;
        else
            upper = mid - 1;
    }
    return -1;
}

Calling it with binarySearchString(words, "bbb", 3);binarySearchString(words, "bbb", 3); returns -1 .返回-1

int main()
{
    vector<string> words;
    words.push_back("aah");
    words.push_back("aal");
    words.push_back("aas");

    int retVal = binarySearchString(words, "bbb", 3);

    std::cout << "Returned: " << retVal << std::endl;

    system("pause");
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM