D1X
D1X

Reputation: 5444

Dynamic array of static arrays

I want a program that creates an undetermined amount of lists. The size of each list is fixed, but I can't determine at compile time how many lists am I going to need.

I understand I cannot create a vector of arrays. I also understand I can use a vector of vectors, but I wonder if this is the best efficient way to do it considering the fact I need to reserve a fixed amount of memory each time I need a new array.

Upvotes: 0

Views: 398

Answers (2)

Felix Bytow
Felix Bytow

Reputation: 345

@Nim is right, but I cannot upvote yet :p Also his solution is C++11.

Another alternative which is to be preferred over std::vector<std::vector<T> > is to have one vector with the dimensions X * Y. Then you can access your elements with v[y * Y + x];

This works with all versions of C++ and should be just as efficient as the std::vector<std::array<T, N> > solution.

Upvotes: 2

Nim
Nim

Reputation: 33655

Erm, you can use a vector of arrays, for example,

std::vector<std::array<T, N>> some_vec;

Upvotes: 5

Related Questions