Rob Boc
Rob Boc

Reputation: 3

Contiguous allocation of objects using STL vector

I need to create objects dynamically and would like to use vectors to do that. I understand that the pointers to the objects would be stored in the vector and they would be contiguous but the actual object will not be. I can do it as given in Create objects in pre-allocated memory . However, I would prefer to use vectors. Is there any way I could do so?

Upvotes: 0

Views: 261

Answers (2)

Iuri Covalisin
Iuri Covalisin

Reputation: 645

Use custom allocator while creating the vector. Your allocator can pre-allocate memory the way you need it.

Upvotes: 0

LihO
LihO

Reputation: 42083

"I need to create objects dynamically"

Are you REALLY sure you NEED the dynamic allocation? If it is possible, use vector of objects instead:

std::vector<T> myObjects(100);

this allocates the single block of memory big enough to hold 100 instances of T and initializes them using the default constructor.

Upvotes: 1

Related Questions