c++ - 如何将向量添加到我的结构中以创建一个库存系统,在该系统中我可以仅使用一个结构将多种不同的葡萄酒添加到系统中?
问题描述
我有一个学校作业,我必须创建一个葡萄酒库存系统,用户可以在其中添加多种不同的葡萄酒,而我假设的数量没有有限。
我需要创建向量,但我不确定。我不知道该尝试什么。
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct Wine1
{ //struct for Wine pssibly needs Vector
string name;
string year;
string place;
string price;
} wine;
void printwine(Wine1 wine);
int main()
{
string str; //input for data
cout << "Please enter the data of the First wine: " << endl;
cout << "Enter name: ";
getline(cin, wine.name);
cout << endl << "Enter year: ";
getline(cin, wine.year);
cout << endl << "enter country of creation: ";
getline(cin, wine.place);
cout << endl << "enter price: ";
getline(cin, wine.price);
cout << endl;
cout << "your entered data: " << endl;
printwine(wine);
cout << endl;
printwine2(wine2);
cout << endl;
printwine3(wine3);
}
void printwine(Wine1 wine)
{ //data the user typed as output
cout << "Wine1" << endl;
cout << "the name is: " << wine.name << endl;
cout << "it's year is: " << wine.year << endl;;
cout << "its country of creation is: " << wine.place << endl;;
cout << "it's price is: " << wine.price << endl;
}
它应该为添加的每种葡萄酒输出葡萄酒的名称、年份、国家和价格。
解决方案
一个好的开始应该是使用的向量Wine1
。
std::vector<Wine1> wineVec;
wineVec.reserve(/*size*/) // reserve the memory if you know the number of wines beforehand
该printwine
函数现在应该采用std::vector<Wine1>
(最好const-reference
是因为数据是只读的)并遍历向量以打印Wine1
.
就像是:
#include <string>
#include <iostream>
#include <vector>
void printwine(const std::vector<Wine1>& vecWine)
{
for (const auto& wine : vecWine)
{
// do printing each: wine.name, wine.year,... so on
}
}
int main()
{
std::vector<Wine1> vecWine;
int wineNumber = 2;
vecWine.reserve(wineNumber);
std::string name, year, place, price;
for (int i = 0; i < wineNumber; ++i)
{
// get the user input for name, year, place, and price
std::cin >> name >> year >> place >> price;
vecWine.emplace_back(Wine1{ name, year, place, price });
}
printwine(vecWine);
}
也就是说,您应该阅读更多内容std::vector
以了解更多信息,它是如何工作的。
此外,很好地阅读,如何重载operator>>
和operator<<
,这样你甚至可以编写代码,更简单。
以下是一个不完整的代码,我在涵盖了我提到的主题后让您完成。
void printwine(const std::vector<Wine1>& vecWine)
{
for (const auto& wine : vecWine)
{
std::cout << wine << '\n';
}
}
int main()
{
std::vector<Wine1> vecWine(wineNumber);
for (Wine1& wine : vecWine)
{
std::cin >> wine;
}
printwine(vecWine);
}
推荐阅读
- wordpress - 安装了 SSL 的 Chrome 显示“不安全”
- c# - 拆分错误以在asp.net c#中检索整数
- c# - 在 autofac 中注册 GlobalConfiguration.Configuration.DependencyResolver
- python-3.x - 如何在每次迭代后减小 ndarray 的大小?
- javascript - 如何克隆输入类型的文件内容?
- vba - Excel VBA 运行时错误
- ios - 当它不是 rootviewcontroller 并且没有导航控制器时,如何从 SKScene 访问以前的视图控制器?
- button - 使用引导程序使用移动设备时如何使按钮组成为下拉列表
- python - 如何在 Keras 中设置一维卷积和 LSTM
- python - Python Selenium:循环浏览网页元素并与之交互