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?
source to share
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
}
source to share