【问题标题】:how to resize a vector which is a member of struct or class?如何调整作为结构或类成员的向量的大小?
【发布时间】:2017-12-23 20:31:30
【问题描述】:

我已经编写了一个结构和类,我想知道如何使用从文本文件中读取的值调整它们的大小。这是结构和类:

typedef struct Chrom // creating the chrom structure
{
  vector<vector <short int> > bit;
  vector<vector <short int> > WaitingTime; //this is wij in the model
  vector<vector <short int> > WaitingJob;//this is wj in the model, sigma wij must be equal to wj for each job J.
  vector<vector <short int> > StartTime;

  short int FinishTime;// finish time of each job in each machine
  int fit;
} chrom;    

在程序中我读到一个数字是 m。 但是在程序中我尝试使用chrom.ShortTime.resize(m)。它给了我一个错误。甚至我试图写一个这样的类:

class ProblemConstraint{ 
  short int Jobs, Machines;
public:
  vector <short int> Processing;
  vector <short int> t1;
  vector <short int> t2;
  short int M;
  short int W;
  void set_values(int, int);
  void resize(){
    ProblemConstraint.Processing.resize(Machines);
  }
}ProblemConstraint;

但我无法调整类中向量的大小。关于如何在程序中的类或结构中调整向量大小的任何建议?

【问题讨论】:

  • 你得到什么错误?
  • "typedef struct Chrom" - 在 C++ 中你不需要 typedef,那是 C 主义。
  • ProblemConstraint.Processing ProblemConstraint 是类型名称,而不是使用点运算符的类实例。在类内部,您可以直接访问成员,这不需要ProblemConstraint.,或者您可以使用this 指针this-&gt;Processing 显式访问它们
  • 关于您的问题:阅读基本教程。这是标准的东西。如果您在这里得到直接答案,这仅意味着您将在下一个任务中失败。阅读基础教程。也就是说,我建议您将代码放在 CodeReview 上。有几个问题。以大写字母开头的变量名、公共成员、未声明为 const 的参数,仅举几例。

标签: c++ class vector struct


【解决方案1】:

你的问题至少部分是你如何称呼它。

void resize(){
    ProblemConstraint.Processing.resize(Machines);
}

应该是这样的:

void resize(){
    Processing.resize(Machines);
    // OR
    this->Processing.resize(Machines);
}

任何地方都没有名为“ProblemConstraint”的对象,那是一种类型,所以你不能在它上面使用.。

【讨论】:

  • “在任何地方都没有名为“Processing”的对象” - 你是说“ProblemConstraint”吗?
  • @vu1p3n0x 是的。该死的错别字。编辑
【解决方案2】:

Kevin Anderson 已解决您的 class 定义问题 - 让我解决结构定义问题:-

使用typedef,您基本上所做的是定义了struct Chrom 类型的chrom 类型,因此您的chrom.StartTime 是无效访问。您必须先实例化chrom 类型的变量,然后才能访问各个成员。试试这个:-

chrom A;
A.StartTime.resize(10);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多