基于用户输入搜索存储在矢量内的库存
Searching an inventory stored within a vector based upon user input
我被要求编写一个搜索库存函数,该函数将搜索基于其模型制作的向量,并将其索引位置返回给用户。我一辈子都想不出如何用数组以外的向量来实现这一点。请帮忙!
//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()
。
对未来的提示:一些函数是缩进的,其余的则不是,这使得最初很难弄清楚。在发布之前努力完全格式化代码是值得的。
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- 有根的二进制搜索树.保留与其父级的链接
- C++:将控制台输出存储在宏中更好吗
- 在C++中搜索嵌套多映射值
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 将值存储在带有C++的二叉搜索树中
- 如何使用 stl 容器有效地存储对象?(即根据其字段的值进行搜索)
- 如何使存储数组的二进制搜索稳定
- 数组 存储并要求用户搜索它
- 基于用户输入搜索存储在矢量内的库存
- 存储和搜索大型数据集
- 看似有效的算法,用于在不浪费空间的情况下将二叉搜索树存储在数组中
- 在C++中存储和搜索数字的最佳方式
- 如何搜索字符串是否是存储在集合中的字符串的前缀
- 二进制搜索树迭代预序遍历,无需额外存储
- 如何使用链表来存储表,并在表中搜索项
- 在堆栈中搜索值并存储在临时堆栈中
- 在C++中存储和搜索短语的最佳数据结构
- 数据结构+算法为ipv4存储高效搜索前缀