If there are too few initialisers, for example:
1 2 3 4 5 6 7 8 9 10
|
int main()
{
std::size_t i = 2, j = 3, k = 4 ;
// std::cin >> i >. j >> k ;
std::vector<int> v = {1,2,3,4,5}; // *** too few initialisers (six are required)
auto vec2 = make_vector( v, i, j ); //, k ) ;
// ...
}
| |
the code, as it is would engender undefined behaviour.
http://coliru.stacked-crooked.com/a/84084805283e1f12
There would also be undefined behaviour if one of the dimensions is zero
vec.resize(v.size()/dims.back()) ; // *** dims.back() == 0
A minor refinement would be to pass the vector containing the initialisers by value
(and then move lvalues into the function).
I would favour factoring the code into two separate functions:
1.
make_vector, which creates the vector with the appropriate dimensions (default initialised)
2.
fill_vector, which fills the innermost vectors with the initialisers
And then, a wrapper
make_filled_vector which chains the calls to
make_vector and
fill_vector
> Can you give me the right syntax in order to make "make_vector" to receive dims as a
> std::vector<size_t> instead of individually?
We are programming in a statically typed language; the type of the result of
make_vector must be known at compile time (and that depends on the number of dimensions). The size of a
std::vector<size_t> is technically known only at run-time.
There is no elegant way to do this; one would have to resort to the equivalent of switching on the number of dimensions, and wrapping the result in a
std::any or
std::experimental::any