How to create 2d array c++?

后端 未结 5 2055
无人共我
无人共我 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: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 > 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

提交回复
热议问题