繁体   English   中英

如何创建2d数组c ++?

[英]How to create 2d array c++?

我需要在c ++中创建2d数组。

我不能通过int mas= new int[x][y];来做到这一点int mas= new int[x][y]; 或者auto mas= new int[x][y]; 我需要动态创建一个数组,如:

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

请帮我。

用于创建动态大小的数组的C ++工具名为std::vector 然而,矢量是一维的,因此为了创建矩阵,解决方案是创建矢量矢量。

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

它不是最有效的解决方案,因为您需要支付每行不同大小的能力。 您不想为此“功能”付费,您必须编写自己的二维矩阵对象。 例如...

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];
    }
};

然后你可以使用它

 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;
int x,y;
x =3;
y = 5;
int ** mas = new int*[x];
for (int i=0;i<x;i++)
{
   mas[i] = new int[y];
}

我觉得这样的事情。 别忘了

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

在末尾。

我的建议是首先避免多维数组的痛苦并使用结构。

struct Point {
    int x;
    int y;
}

int points = 10;
Point myArray[points];

然后访问一个值:

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

但是,这取决于你想要实现的目标。

你可以自己动手操作。

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

和访问[i,j]:

mas[i*y + j] = someInt;
otherInt = mas[i*y +j];
std::vector<std::vector<int> >  mas(y, std::vector<int>(x));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM