【问题标题】:Searching an inventory stored within a vector based upon user input [closed]根据用户输入搜索存储在向量中的库存[关闭]
【发布时间】:2016-05-07 10:49:23
【问题描述】:

我被要求编写一个搜索清单函数,该函数将根据其模型搜索向量,并将其索引位置返回给用户。我一生都无法弄清楚如何使用数组以外的向量来做到这一点。请帮忙!

//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();

}

【问题讨论】:

    标签: c++ vector binary-search


    【解决方案1】:

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

    接下来返回类型错误。您正在返回 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*/);
    

    一旦你让它工作起来,可能值得在code review获得更多建议

    【讨论】:

    • 这是我第一次在这里提出问题,所以我的代码有点不对劲。谢谢你的cmets!我还在为如何返回“索引位置”而苦苦挣扎
    • @That1GirlProgrammer:你用return position; 做得很好。索引只是数据所在数组的偏移量。
    【解决方案2】:

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

    另外,仅供参考,return 语句后不会执行任何操作,因此此处不使用 cin.ignore()。

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

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 2012-07-25
      相关资源
      最近更新 更多