C ++是一个具有结构数组的类,不知道我需要多大的数组 [英] C++ a class with an array of structs, without knowing how large an array I need

查看:220
本文介绍了C ++是一个具有结构数组的类,不知道我需要多大的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程,像 ,名字,年龄,学校等。我需要能够存储其他信息,例如他们已经旅行过的年份,以及它在哪一年。不能声明另一个类专门持有travelDestination和什么年份,​​所以我认为一个结构可能是最好的。这只是一个例子:

I have a class with fields like firstname, age, school etc. I need to be able to store other information like for instance, where they have travelled, and what year it was in. I cannot declare another class specifically to hold travelDestination and what year, so I think a struct might be best. This is just an example:

struct travel {
    string travelDest;
    string year;
};

问题是人们可能已经走过不同的金额。我正在考虑拥有一系列旅行结构来保存数据。但是,如何创建一个固定大小的数组来保存它们,而不知道我需要多大的数量?

The issue is people are likely to have travelled different amounts. I was thinking of just having an array of travel structs to hold the data. But how do I create a fixed sized array to hold them, without knowing how big I need it to be?

也许我会这样做是完全错误的,所以对于一个更好的方法的任何建议将不胜感激。

Perhaps I am going about this the completely wrong way, so any suggestions as to a better way would be appreciated.

我意识到类和结构之间基本没有区别,但是为了分配标准的目的,我不允许一个类,所以是的。

I realise there is essentially no difference between a class and struct, but for the purposes of assignment criteria I am not allowed a "class", so yeah.

推荐答案

你可以尝试关联一个<每个人的一个href =http://www.cplusplus.com/reference/stl/vector/ =nofollow noreferrer> std :: vector ,向量中的每个条目都包含一个结构体:

You could try associating a std::vector with each person, with each entry in the vector containing a struct:

typedef struct travel {
    string travelDest;
    string year;
} travelRecord;

std::vector<travelRecord> travelInfo;

然后,您可以根据需要向矢量添加项目:

You can then add items to the vector as you see fit:

travelRecord newRecord1 = {"Jamaica", "2010"};
travelInfo.push_back(newRecord1);

travelRecord newRecord2 = {"New York", "2011"};
travelInfo.push_back(newRecord2);

有关向量操作的更多信息可以找到这里

Some more information about vector operations can be found here.

这篇关于C ++是一个具有结构数组的类,不知道我需要多大的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆