How to determine the size of a member at runtime

Say I have a class that has a member that is an array. Is it possible to determine its size when building / at runtime, as follows:

class myClass {
    private:
        int myArray[n]
    public:
        myClass();
        someOtherMethod();
};

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

+3
source share
3 answers

Use a vector.

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

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

Then you can fill the vector in the same way as an array. Alternatively, as Nawaz points out, use reserve()one that reserves space for new items and / or push_back()that adds items to the back one at a time.

+3
source

It depends.

Semantically there are 3 types of arrays:

  • ,
  • ,

++ , , std::vector.

C :

  • ( )
  • oldie

++ std::vector . , , .

, , ++. .

+5

std::vector .

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

myClass::myClass(int size) : myArray(size)
{
}
+1

All Articles