When I read some values from the user and I need to create an array of the specific size I do it somehow like this:
#include
using namespace
Although the "vector of vectors" solution can be satisfying, they are not a 2D structure: each "row" will be allocated independently of another, and length can be different row by raw (and hence the 2D constrain must be maintained manually: inserting an item requires all rows to be enlarged so that elemets that are one above the other maintain their relative position.
In case you need a proper dynamic 2D structure, you can wrap a vector (simple mono-dimensional) in a class (let's call it "table
") and provide that class with the operation requird to properly maintain it as an externally represented 2D. In particular:
Colums() const
and Rows() const
functions retuning theactual size of the table.int& operator()(unsigned row, unsigned col) { return vect[row*Colums()+col]; }
and it s const counterpartstruct coord { unsigned r, unsigned c }
and a convenient table::operator[](const coord&)
insert
and remove
methods to insert a row (just insert Colums()
consecutive elements at r*Columns()
) and a column (insert one element every Columns()+1
starting from c
)end()
value for them)The key point of all this stuff is the understanding of the n = r*C+c
formula at the second point. Everything else is just an almost immediate consequence.
Anything that would look like a 2D-Array in code will not be a physical 2D array in memory, but either one plain block of memory or scattered, depending on how you allocate it.
Brennan Vincent's answer suggests allocation of one dynamic array, containing a*b elements, which gives you one continuous block in memory. Combine that with the builtin dynamic memory management of std::vector
he mentioned and be happy:
std::vector<unsigned> matrix(a*b);
If you want the matrix to be convenient to access, wrap the whole thing into a class providing you access to the elements with 2D-coordinates. But please step away from managing the memory yourself. It just hurts you and anyone who has to maintain that code (and search for mem leaks).