基于用户输入搜索存储在矢量内的库存

Searching an inventory stored within a vector based upon user input

本文关键字:存储 搜索 于用户 用户 输入      更新时间:2023-10-16

我被要求编写一个搜索库存函数,该函数将搜索基于其模型制作的向量,并将其索引位置返回给用户。我一辈子都想不出如何用数组以外的向量来实现这一点。请帮忙!

//this function will search the inventory and return its index position.        
void searchInventory(vector<Vehicle> &vehicles)
{
    int invSize = vehicles.size();
    string vModel;
    int position = -1;
    int index = 0; //position of search
    bool found = false; //flag
cout << "Please enter the model number of the vehicle you are searching for: " << endl;
getline(cin, vModel);
while (index < invSize && !found)
{
    if (vehicles[index].getModel == vModel)
    {
        found = true;
        position = index;
    }
       index++;
}
  return position;
  cin.ignore();
}

首先要做的是很好地格式化代码。

接下来,返回类型是错误的。您正在返回一个int,但函数的返回类型是void。此外,你的评论也不太正确。如果你找不到任何值,你会返回一个超过向量末尾的值(这是C++中的常见做法,但你应该提到它)。

void searchInventory(vector<Vehicle> &vehicles)

有几种方法可以循环通过向量。

while (index < invSize && !found) {
       // STUFF
       index++;
}

for(int index = 0; index < invSize && !found; ++index) {
     // STUFF
}

for(auto loop = std::begin(vehicles); loop != std::end(vehicles); ++loop) {
    // STUFF
}

for(auto const& item: vehicles) {
    // STUFF
}

还有一些搜索容器的标准函数。

std::find(std::begin(vehicles), std::end(vehicles), /*Test*/);

一旦你让它工作起来,可能值得在代码审查

中获得更多建议

函数的返回类型为void,但返回的是一个整数。

此外,仅供参考,return语句之后将不执行任何内容,因此此处不使用cin.ignore()

对未来的提示:一些函数是缩进的,其余的则不是,这使得最初很难弄清楚。在发布之前努力完全格式化代码是值得的。