Create variable number of vectors in C ++
I can create a 2D-array of size n*m
, running:
vector< vector< int > > foo(n, vector< int > (m))
.
Suppose I am assigned a variable number of values ββat runtime, for example v_1, v_2, v_3, ..., v_k
and want to create the following:
vector< vector< ... vector< int > ... > > foo(v_1, vector< ... > (v_2, vector< ... > ..));
In other words, create a multidimensional array of size v_1* v_2 * v_3 ... *v_k
. How can i do this? Is it possible?
You cannot do this - the data type must be set at compile time. However, it is quite practical to use a single array with the correct count of all elements and create a mapping so that your boolean is [i1][i2][...]
found with a name [i1*v2*v3...vk + i2*v3..vk + ...]
.
You need someone boost::variant
who can handle this. You can create a recursive_wrapper that allows you to nest content arbitrarily. There are other approaches, such as one large flat array, or you can use inheritance and dynamic allocation, but they take quite a lot of hassle.
typedef boost::variant<
int,
std::vector<boost::recursive_variant_>
> variant;
int main() {
std::vector<variant> var; // Assume at least 1 dimension
}