I need to create 2d array in c++.
I can\'t do it by int mas= new int[x][y];
or auto mas= new int[x][y];
I need to create an array dynamical
The C++ tool for creating dynamically sized arrays is named std::vector
. Vector is however one-dimensional, so to create a matrix a solution is to create a vector of vectors.
std::vector< std::vector > mas(y, std::vector(x));
It's not the most efficient solution because you pay for the ability to have each row of a different size. You you don't want to pay for this "feature" you have to write your own bidimensional matrix object. For example...
template
struct Matrix
{
int rows, cols;
std::vector data;
Matrix(int rows, int cols)
: rows(rows), cols(cols), data(rows*cols)
{ }
T& operator()(int row, int col)
{
return data[row*cols + col];
}
T operator()(int row, int col) const
{
return data[row*cols + col];
}
};
Then you can use it with
Matrix mat(y, x);
for (int i=0; i