The simplest way is to use nested std::vector
(s) and an initializer_list
.
Dynamically allocated multidimensional array are quite error prone.
E.g. if you look closely at your example you'll see that the correct code for a [2][5] matrix is:
int **matrix = new int*[2];
for(int i(0); i < 2; ++i)
matrix[i] = new int[5];
If you really want a matrix, probably neither std::vector<std::vector<int>>
nor int** matrix
are good layouts (the main problem is that you lose data locality).
A classic solution that works quite nicely is a wrapper around a single vector, that keeps track of the "shape" of the matrix being represented and provides an operator to access the data:
class matrix
{
public:
matrix(unsigned rows, unsigned columns)
: columns_(columns), data_(columns * rows)
{}
matrix(std::initializer_list<std::initializer_list<int>> lst)
: matrix(lst.size(), lst.size() ? lst.begin()->size() : 0)
{
unsigned i(0), j(0);
for (const auto &l : lst)
{
for (const auto &v : l)
{
operator()(i, j) = v;
++j;
}
j = 0;
++i;
}
}
int &operator()(unsigned row, unsigned column)
{ return data_[row * columns_ + column]; }
private:
unsigned columns_;
std::vector<int> data_;
};
and you can write:
matrix m = {
{1,8,12,20,25},
{5,9,13,24,26},
};