Reputation: 5479
I can create a 2D array of size n*m
by doing:
vector< vector< int > > foo(n, vector< int > (m))
.
Suppose that at runtime I'm given a variable number of values,
e.g. 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 this possible?
Upvotes: 3
Views: 1506
Reputation: 147036
You need boost::variant
, which can handle this. You can create a recursive_wrapper that will allow you to nest the contents arbitrarily. There are other approaches, such as one single flat array of large size, or you can use inheritance and dynamic allocation, but they involve quite a bit more hassle.
typedef boost::variant<
int,
std::vector<boost::recursive_variant_>
> variant;
int main() {
std::vector<variant> var; // Assume at least 1 dimension
}
Upvotes: 4
Reputation: 106244
You can't do this - data type must be set at compile time. That said, it's quite practical to use a single array with the correct total number of elements, and create a mapping so that your logical [i1][i2][...]
is found at say [i1*v2*v3...vk + i2*v3..vk + ...]
.
Upvotes: 4