如何定义在运行时成员数组的大小

如何定义在运行时成员数组的大小

本文介绍了如何定义在运行时成员数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有,有一个成员是一个数组类。是否有可能定义构造时其尺寸/在运行时,以下列方式:

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();
};

其中n是基于用户输入定义的变量。如果不是这样,这将是最好的选择?

Where n is a variable that is defined based on user input. If not, what would be the best alternative?

推荐答案

使用向量。

class myClass {
    private:
        std::vector<int> myArray;
    public:
        myClass();
        someOtherMethod();
};

myClass::myClass (int size)
    : myArray (size)
{
    ...
}

然后,您可以在矢量,你会数组填补。或者,纳瓦兹指出,使用储备(),它保留空间新的元素,和/或的push_back(),这增加了元件到背面,一次一个。

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.

这篇关于如何定义在运行时成员数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:34