簡體   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