rasul1719435
rasul1719435

Reputation: 115

Create array of object as user requirement increase?

I would like to know is possible to create arrays as user requires. For example

  1. I ask the user "Do you want coffee" 2.if the user say yes and i create a array of coffee object. .....
  2. I ask the user "Do you want to have another coffee"?
  3. if user say yes than i create another array of coffee class if not i dont create.

Is this achieveable or must i create a fixed number of array?

Upvotes: 0

Views: 118

Answers (2)

iammilind
iammilind

Reputation: 69998

You cannot create fixed size array at runtime in C++, except some compilers (like g++) provides extension for VLA.

Use std::vector instead. It grows as per your control and automatically deallocates itself when requirement is done.

Edit: As the std::vector cannot be used by the asker, following is the way using new[] with 'some' pseudo code:

Coffee **pQuestions = new Coffee* [n]; // n - number of times coffee is asked
for(uint i = 0; i < N; ++i)
{
  /* ask for Coffee */
  if(/* yes */)
    pQuestion[i] = new Coffee[size]; // whatever array size you want
}

Here n and size are variables(can or cannot be constants) as per your need

Later when you are done, deallocate all the memory as delete[] pQuestions[i]; and delete[] pQuestions;.

Upvotes: 2

You can use standard container classes like std::vector which gives you resizeable vectors of some arbitrary but given type. Of course, you can have vectors of vectors, or vectors of queues, etc.

(You could use manually allocated pointers and code à la C, but you'll better use the powerful containers provided by the STL).

Upvotes: 0

Related Questions