Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable number of vectors in C++

Tags:

c++

vector

I can create a 2D array of size n*mby 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?

like image 819
insumity Avatar asked Jan 14 '23 09:01

insumity


2 Answers

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 + ...].

like image 133
Tony Delroy Avatar answered Jan 22 '23 13:01

Tony Delroy


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
}
like image 25
Puppy Avatar answered Jan 22 '23 14:01

Puppy