How to create 2d array c++?

后端 未结 5 2054
无人共我
无人共我 2020-12-10 21:05

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

相关标签:
5条回答
  • 2020-12-10 21:19

    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.

    0 讨论(0)
  • 2020-12-10 21:21
    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.

    0 讨论(0)
  • 2020-12-10 21:21

    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;
    
    0 讨论(0)
  • 2020-12-10 21:30

    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];
    
    0 讨论(0)
  • 2020-12-10 21:36
    std::vector<std::vector<int> >  mas(y, std::vector<int>(x));
    
    0 讨论(0)
提交回复
热议问题