如何解决在C ++中创建无限对象并将其添加到数组中
例如,我有一个名为“患者”的对象。我一天之内的病人数不明,并且必须将这些病人记录保存一周。
对于如何进行此操作,我颇有想法。如何创建无限对象(例如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
。 -
=
是一个赋值运算符。您应该使用==
检查是否相等。
这些注释也适用于上面的代码。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。