首页 > 解决方案 > 如何将向量添加到我的结构中以创建一个库存系统,在该系统中我可以仅使用一个结构将多种不同的葡萄酒添加到系统中?

问题描述

我有一个学校作业,我必须创建一个葡萄酒库存系统,用户可以在其中添加多种不同的葡萄酒,而我假设的数量没有有限。

我需要创建向量,但我不确定。我不知道该尝试什么。

#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;
}

它应该为添加的每种葡萄酒输出葡萄酒的名称、年份、国家和价格。

标签: c++classc++11data-structuresstdvector

解决方案


一个好的开始应该是使用的向量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);
}

推荐阅读