allocating vectors (or vectors of vectors) dynamically

Dynamically allocating arrays is required when your dimensions are given at runtime, as you’ve discovered.

However, std::vector is already a wrapper around this process, so dynamically allocating vectors is like a double positive. It’s redundant.

Just write (C++98):

#include <vector>

typedef std::vector< std::vector<double> > matrix;
matrix name(sizeX, std::vector<double>(sizeY));

or (C++11 and later):

#include <vector>

using matrix = std::vector<std::vector<double>>;
matrix name(sizeX, std::vector<double>(sizeY));

Leave a Comment