C++ 中的二进制搜索实现

Binary Search Implementation in C++

我编写了一个程序,它应该执行以下操作:

read product item data from an inventory file and add them in a vector object. The program will allow user to view, search and order the product items. The inventory file should be updated after the order of any item.

  • For operation #2 (searching) and #3 (ordering), appropriate messages should be displayed for the input of invalid item name, then program should proceed to process next operation

预期输出:

>: 2
Enter the item name to search: table
table not found.

>: 2
Enter the item name to search: Microwave
Microwave is in stock.
  • For operation #3 (ordering), program should validate the input number of order and make sure there are enough items in the inventory. Otherwise, display error message and skip the ordering –

预期输出:

>: 3
Enter the name of the item: Microwave
Enter the nuber of items: 100
Insufficient inventory.

>: 3
Enter the name of the item: Microwave
Enter the nuber of items: 2
Total cost is 0

>: 3
Enter the name of the item: table
table not found.

但是当我尝试使用二进制搜索按名称搜索项目的名称时,它没有给我想要的结果,例如:

1.

>: 2
Enter the item name to search: Cooking Range
Cooking Range not found.
>: 2
Enter the item name to search: Circular Saw
Circular Saw not found.

这是包含数据的文件:

itemData.txt

1111
Dish Washer
20 550.5
2222
Microwave
75 150
3333
Cooking Range 
50 850
4444
Circular Saw
150 125

这是我尝试实现的按名称搜索项目的函数的定义:

int
searchItemByName(vector<Item> items, string searchName)
{
    int low, high, mid;

    low = 0;
    high = items.size() - 1;
    while (low <= high) {
        mid = (low + high) / 2;

        if (items[mid].getName() == searchName)
            return (mid);
        else if (items[mid].getName() > searchName)
            high = mid - 1;
        else
            low = mid + 1;
    }
    return (-1);
}

这是整个程序(我还添加了一个更清晰、更广泛的“描述”,说明程序应该如何处理一些测试。):

https://github.com/jrchavez07/project_07

我检查了你的 GitHub 项目。

我认为你必须在二进制搜索之前对数据进行排序。

示例文本文件列表中的当前数据如下:

Dish Washer
Microwave
Cooking Range 
Circular Saw

而且这些都没有排序,所以不能使用二分查找。