user1828256
user1828256

Reputation: 25

need to create multiple dynamic arrays in c++

I need to create a number of arrays of a certain object where the number I need is dependent on a separate variable the best way to explain it is with a psudo code example:

int num = 4;
for(int i=0;i<num;i++){
   object_type arrayi [dynamic size];
}

So i need 4 arrays each with the names array0,array1,array2, and array3 and they must all be dynamic arrays. Is there anyway to do this in C++?

Upvotes: 0

Views: 3715

Answers (4)

Cassio Neri
Cassio Neri

Reputation: 20503

Reading the OP again, it seems to me that the number of arrays is not known at compile time. In this case, you can use a std::vector<std::vector<object_type>>:

#include <vector>
// ...
// int num = ???, dynamic_size = ???;
std::vector<std::vector<object_type>> vs(num);
for (auto& v: vs)
    v.resize(dynamic_size);

then you can use vs[i][j] to get a reference to the j-th element of the i-th array (vector).

Piece of advise: Don't use this (std::vector<std::vector<double>>) for linear algebra matrices.

Bonus: In C++14 (actually this is a C99 feature that some compilers allow in C++ as an extension) you'll be able to do this:

#include <vector>
// ...
// int num = ???, dynamic_size = ???;
std::vector<object_type> vs[num];
for (auto& v: vs)
    v.resize(dynamic_size);

For more information see this post.

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

std::array<std::vector<object_type>, 4> array;
for (auto & v : array)
    v.resize(dynamic_size);

The names are array[0], array[1], etc... instead of array1, array2, etc... But who cares? If you absolutely must have those names, then Cassio's answer is your best bet.

Pre C++11 alternative:

std::vector<object_type> array[4];
for (size_t i=0; i<4; ++i)
    array[i].resize(dynamic_size);

If you want a variable number of arrays, then you can use a vector of vectors, and actually, the initialization for that is even easier. It doesn't require a loop, you can do it in the constructor.

std::vector<std::vector<object_type>> array(num, std::vector<object_type>(dynamic_size));

Upvotes: 5

John
John

Reputation: 16007

If there is a way to dynamically create variables like the way you want within C++, I haven't heard of it.

If performance is an issue and you need to construct a bunch of 1-d arrays (rather than an array of arrays or a vector of arrays) then you could do code generation at build time to make as many as you want. That's outside of C++ though; it's a pre-build command that outputs a C++ text file.

If performance isn't an issue, then constructing a vector of arrays like Benjamin has done will work great.

Upvotes: 0

SinisterMJ
SinisterMJ

Reputation: 3509

Yes, use std::vector<object_type> instead. You can resize to an arbitrary size. Otherwise for arrays you can use dynamic allocation with

ObjectType* myArray = new ObjectType[number];

but using std::vector instead is recommended.

Upvotes: 2

Related Questions