[16.20] Does C++ have arrays whose length can be specified at run-time?
Yes, in the sense that the standard library has a std::vector
template that provides this behavior.
No, in the sense that built-in array types need to have their length specified
at compile time.
Yes, in the sense that even built-in array types can specify the first index
bounds at run-time. E.g., comparing with the previous FAQ, if you only need
the first array dimension to vary then you can just ask new for an array of
arrays, rather than an array of pointers to arrays:
const unsigned ncols = 100; // ncols = number of columns in the array
class Fred { /*...*/ };
void manipulateArray(unsigned nrows) // nrows = number of rows in the array
{
Fred (*matrix)[ncols] = new Fred[nrows][ncols];
...
delete[] matrix;
}
You can't do this if you need anything other than the first dimension of the
array to change at run-time.
But please, don't use arrays unless you have to. Arrays
are evil. Use some object of some class if you can. Use arrays only
when you have to.