Link to home
Start Free TrialLog in
Avatar of Rothbard
RothbardFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Array/vector class member of variable size

How is it possible to have a class with an array (or vector) as a class member, whose size is unknown in advance? Say one of the class members must be an array of times t0, t1, .... tN. However we don't know N until we create an instance of the class.
Avatar of ikework
ikework
Flag of Germany image

you can either use stl::vector or pass the array size to the class and create the c-array then, here is the latter:

class Times
{
public:

};
Hi Rothbard,

Absolutley.

Consider the TList object.  It is a list of arbitrary length of pointers to objects that the programmer passes to the class.  The objects are user defined with the class having no knowledge of the underlying data structure or size.

You can certainly do the same thing with your own classes.



Good Luck,
Kent
you can use a STL vector<> class, you just create it empty, then you can add items or separate some room for elements furtherly.
Do you know about it?
sorry .. my browser was too fast .. ;)

class Times
{
public:
    Times( int size )
    : m_size( size )
    {
        m_array = new float[m_size];
    }
    ~Times()
    {
        delete[] m_array;
    }

    float& GetTimeAt( int idx ) { return m_array[idx]; }

private:
    float *m_array;
    int      m_size;
};

ASKER CERTIFIED SOLUTION
Avatar of ikework
ikework
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rothbard

ASKER

Thanks a lot for all your replies, guys. I gave the points to the answers I found most useful for what I need to do.