如何在数组C++中存储未知数量的元素

Alt*_*ber 1 c++ arrays store dynamic

对不起,如果标题不清楚,我现在解释我的问题.我是C++的新手.

我用C++创建了一个类.该类的实例是程序的输入,它们必须存储在数组中以执行计算.问题是,必须由用户定义的该类的实例数量对于单次运行是固定的,但可能因运行而异.这是一个例子:

#include <<blablah>blahblah>

int main()
{
int number_of_instances = 3;

MyClass first_instance(one_parameter_1, another_parameter_1);
MyClass second_instance(one_parameter_2, another_parameter_2);
MyClass third_instance(one_parameter_3, another_parameter_3);
Run Code Online (Sandbox Code Playgroud)

///////////////////

现在我必须在阵列中存储所有这三个

MyClass array[number_of_instances] = {first_instance, second_instance, third_instance};
Run Code Online (Sandbox Code Playgroud)

问题是我之前不知道手中有多少是用户正在输入的信息

///////////////////

performCalculations(array);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢提前.

DSh*_*ook 6

典型的C++解决方案是使用向量.

vector<MyClass> v;
v.push_back(first_instance);  //add an already instantiated object to the end of the vector
v.push_back(second_instance);
v.push_back(third_instance);
Run Code Online (Sandbox Code Playgroud)

你不必担心内存管理,你可以像普通数组一样访问向量:

v[0].classMember
Run Code Online (Sandbox Code Playgroud)

如果需要,您还可以在循环中向向量中添加项目,如下所示:

for(int i = 0; i < 5; i++){
    v.push_back( MyClass(i, param2) );
}
Run Code Online (Sandbox Code Playgroud)

如果您将对象直接存储在向量中,则当向量超出范围时,所有对象都将被销毁.

将对象直接存储在向量中的缺点之一是将向量作为参数传递给函数.这将是一个缓慢的操作,因为必须复制向量(及其保存的所有对象).