[英]How to define member array size at runtime
Let's say I have a class that has a member which is an array. 假设我有一个具有数组成员的类。 Is it possible to define its size upon construction/at run-time, in the following way: 是否可以在构建时/运行时定义其大小,方式如下:
class myClass {
private:
int myArray[n]
public:
myClass();
someOtherMethod();
};
Where n is a variable that is defined based on user input. 其中n是基于用户输入定义的变量。 If not, what would be the best alternative? 如果没有,最好的选择是什么?
It depends. 这取决于。
Semantically, there are 3 types of arrays: 从语义上讲,有三种类型的数组:
C++ directly supports the first and third cases, respectively with regular arrays and the std::vector
class. C ++直接支持第一种和第三种情况,分别使用常规数组和std::vector
类。
C also supports the second type with two constructs: C还支持带有两个结构的第二种类型:
I would advise, in C++, using the std::vector
class in your case. 我会建议,在C ++中,在你的情况下使用std::vector
类。 It provides more than what you need, but is simpler to use. 它提供的不仅仅是您需要的,而且使用起来更简单。
On the other hand, you can still use tail-padding, even in C++. 另一方面,即使在C ++中,您仍然可以使用尾部填充。 It does require careful engineering though. 它确实需要仔细的工程。
Use a vector. 使用矢量。
class myClass {
private:
std::vector<int> myArray;
public:
myClass();
someOtherMethod();
};
myClass::myClass (int size)
: myArray (size)
{
...
}
Then, you can fill in the vector as you would an array. 然后,您可以像填充数组一样填充矢量。 Alternatively, as Nawaz points out, use reserve()
, which reserves space for new elements, and/or push_back()
, which adds elements onto the back, one at a time. 或者,正如Nawaz指出的那样,使用为新元素保留空间的reserve()
和/或push_back()
,它一次一个地添加元素到背面。
The class template std::vector
is designed for this purpose. 类模板std::vector
就是为此目的而设计的。
class myClass {
private:
std::vector<int> myArray;
public:
myClass(int size);
someOtherMethod();
};
myClass::myClass(int size) : myArray(size)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.