类内结构的 C++ 向量

c++ vector of structs inside class

本文关键字:C++ 向量 结构      更新时间:2023-10-16

大家好,我正在研究一个名为Inventory Inquisitor的学校prject。 规格如下:

在此处输入图像描述

到目前为止,我已经创建了一个类,其中包含该结构的结构和向量。到目前为止,我试图做的只是让类显示结构,只是为了知道它有效,但是当我编译它并运行它时,没有任何反应。这是代码。请原谅我犯的任何菜鸟错误,我对类和向量都很陌生。提前谢谢你!

//Inventory Inquisitor.cpp
#include <iostream>
#include <string>
#include <cctype> //for toupper
#include <fstream>
#include <vector>
using namespace std;
class Inventory
{
  private:
  struct item
   {
  string Description = " ";
  double Quantity = 0;
  double Wholesalescost = 0;
  double Retailcost = 0;
  string Dateadded = " ";
   };
   vector<item> Inv;
public:
  void Display();
};
void Inventory::Display()
{ 
 Inv[0].Description = "english";
 Inv[0].Quantity = 1;
 Inv[0].Wholesalescost = 100;
 Inv[0].Retailcost = 200;
 Inv[0].Dateadded = "3/8/2018";
 cout << Inv[0].Description << endl;
 cout << Inv[0].Quantity << endl;
 cout << Inv[0].Wholesalescost << endl;
 cout << Inv[0].Retailcost << endl;
 cout << Inv[0].Dateadded << endl;
}
int main()
{
 Inventory inst1;
  inst1.Display();
 }

在访问向量之前,您必须将一些内容放入向量中:

// Create an item
item i;
i.Description = "english";
i.Quantity = 1;
i.Wholesalescost = 100;
i.Retailcost = 200;
i.Dateadded = 3/8/2018;
// The vector is empty, size() == 0    
// Add it to the vector
Inv.push_back(i);
// Now the vector has 1 item, size() == 1
// Now you can print it
cout << Inv.at(0).Description << endl;
cout << Inv.at(0).Quantity << endl;
cout << Inv.at(0).Wholesalescost << endl;
cout << Inv.at(0).Retailcost << endl;
cout << Inv.at(0).Dateadded << endl;

根据您的分配,您很可能会更改为打印现有项目的功能。您将有另一个函数将项目添加到向量。

void Inventory::Display(int index)
{ 
    // Print an item already in the vector
    if (index >= 0 && index < Inv.size()) {
        cout << Inv.at(index).Description << endl;
        cout << Inv.at(index).Quantity << endl;
        cout << Inv.at(index).Wholesalescost << endl;
        cout << Inv.at(index).Retailcost << endl;
        cout << Inv.at(index).Dateadded << endl;
    }
}