SevenDays
SevenDays

Reputation: 3768

How to create 2d array c++?

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 dynamically like:

int x,y
auto mas= new int[x][y];//error - must be const.

Please help me.

Upvotes: 3

Views: 9617

Answers (5)

6502
6502

Reputation: 114461

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<int> > mas(y, std::vector<int>(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<typename T>
struct Matrix
{
    int rows, cols;
    std::vector<T> 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<int> mat(y, x);
 for (int i=0; i<mat.rows; i++)
   for (int j=0; j<mat.cols; j++)
     mat(i, j) = (i == j) ? 1 : 0;

Upvotes: 4

ragnarius
ragnarius

Reputation: 5813

std::vector<std::vector<int> >  mas(y, std::vector<int>(x));

Upvotes: 0

Roee Gavirel
Roee Gavirel

Reputation: 19445

You can do the manipulations yourself.

int* mas = new int[x*y];

and access [i,j] by:

mas[i*y + j] = someInt;
otherInt = mas[i*y +j];

Upvotes: 2

Kotodid
Kotodid

Reputation: 1179

int x,y;
x =3;
y = 5;
int ** mas = new int*[x];
for (int i=0;i<x;i++)
{
   mas[i] = new int[y];
}

I think something like this. Don't forget

for(int i=0;i<x;i++)
   delete[] mas[i];
delete[] mas;

at the end.

Upvotes: 4

Ant
Ant

Reputation: 4928

My advice would be to avoid the pain of multidimensional arrays in the first place and use a struct.

struct Point {
    int x;
    int y;
}

int points = 10;
Point myArray[points];

Then to access a value:

printf("x: %d, y: %d", myArray[2].x, myArray[2].y);

Depends on exactly what you're trying to achieve, though.

Upvotes: 2

Related Questions