【问题标题】:c++ vector of structs inside class类内结构的c ++向量
【发布时间】:2018-03-08 21:40:28
【问题描述】:

大家好,我正在从事一个名为库存调查员的学校项目。规格如下:

enter image description here

到目前为止,我已经创建了一个类,其中包含一个结构和该结构的向量。 到目前为止,我所做的只是让类显示结构只是为了知道它可以工作,但是当我编译它并运行它时,什么也没有发生。这是代码。原谅我犯的任何菜鸟错误,我对课程和向量都很陌生。提前谢谢你!

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

 }

【问题讨论】:

  • DisplayInv.size() == 0。您需要将item 放入向量中。
  • 第一次学习使用向量时,请将vector_name[some_number] 替换为vector_name.at(some_number)
  • 感谢您的建议,我似乎不明白您的意思,我用 vector_name.at(some_number) 替换了 vector_name[some_number],现在我收到一个错误,在抛出实例后调用终止of 'std::out_of_range' what(): vector::_M_range_check: __n(即 0)>= this->size()(即 0)

标签: c++ class object vector struct


【解决方案1】:

在访问它之前,你必须在向量中放入一些东西:

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

【讨论】:

  • 非常感谢您的详细解释,我以为我在第 22 行“vector Inv”上使用 Inv 创建了该项目。但现在我明白了。谢谢约翰尼,我很感激!
猜你喜欢
  • 2013-08-14
  • 1970-01-01
  • 2016-02-16
  • 2019-12-01
  • 2023-03-27
  • 2012-10-16
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多