mrsoliver
mrsoliver

Reputation: 111

Create objects in loop for C++

I need create 220 object. The normal creation is like the code below; Is there any way more easy to create them? maybe a for Loop...

const int ID_box1 = 1; 

box1 = new Boxes(ID_box1, position(10,10); 

box1->Append("option 1");
box1->Append("option 2"); etc..

// each box have 80 options:

Upvotes: 0

Views: 141

Answers (1)

Rushikesh
Rushikesh

Reputation: 173

If you are sure about the number of objects to be created, then, you may use array as follows:

#include <array>

std::array<Box, 220> boxes; // assumes default constructor is available for Box class. 

std::array gives performance benefit, it's usage is similar to normal array of objects plus it acts as a container so if needed, the applicable standard library algorithm functions can be used.

If more flexibility, functionality is needed, then, std::vector is good choice.

Upvotes: 1

Related Questions