在C ++中创建无限对象并将其添加到数组中

问题描述

例如,我有一个名为“患者”的对象。我一天之内的病人数不明,并且必须将这些病人记录保存一周。

  1. 我将有一个对象数组来存储一天中的“患者”
  2. 一个大小为7的weekArray可以存储每天的记录吗?

对于如何进行此操作,我颇有想法。如何创建无限对象(例如Patient Patient1,Patient2 ...),直到用户希望跳至第二天并将它们存储在无限大小的数组中?

struct Patient {
  string name; 
  int age;
}

void main (){

/*Im not sure the type for this array and how to assign these patients into this array daily*/ 
?? weekArray [7];
bool continueAdd = true;

  for (int i =0; i<7; i++){
    while (continueAdd){

      //Prompt creation of new object using Patient as object type
      Patient patient1....patientN //I want to only create new object after user wants to add another patient at the end of this loop

      cout<<"Enter name:";
      cin>> ??.name;
      cout<<"Enter age:";
      cin>> ??.age;

      cout<<"Continue adding patient? Y for yes,N to skip to next day";
      char decision;
      cin>>decision;
      if (decision == 'n'){
         continueAdd=false;
      } //assume i hv tolower.

      }
  }
}

我希望这不是我要问的困惑。我想我将需要使用arrayList而不是动态数组。我希望有人能指导我如何进行此操作的结构。

或者,如果有什么方法可以更有效地解决这个问题,我将不胜感激。

解决方法

当要存储的元素数量未知时,应使用std::vector

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::cin;
using std::string;

struct Patient {
  string name; 
  int age;
};

int main (){
  std::vector<Patient> weekArray[7];

  for (int i =0; i<7; i++){
    bool continueAdd = true;
    while (continueAdd){

      //Prompt creation of new object using Patient as object type
      Patient patient;

      cout<<"Enter name:";
      cin>> patient.name;
      cout<<"Enter age:";
      cin>> patient.age;

      //Add this object to the array
      weekArray[i].push_back(patient);

      cout<<"Continue adding patient? Y for yes,N to skip to next day";
      char decision;
      cin>>decision;
      if (decision == 'n'){
         continueAdd=false;
      } //assume i hv tolower.

      }
  }
}

还请注意:

  • 结构声明后需要;
  • 全局main必须在C ++中返回int
  • 您将必须在一周中的每一天的每次循环之前初始化continueAdd
  • =是一个赋值运算符。您应该使用==检查是否相等。

这些注释也适用于上面的代码。