如何使用智能指针在两个维度上声明一个数组?

时间:2018-05-16 04:54:55

标签: c++ arrays smart-pointers

unique_ptr<int> ptr1(new int {});
unique_ptr<int[]> ptr2(new int[5] {});

单个和一维数组可以如上所述声明。如何将二维或更多数组声明为智能指针?

const size_t idx = 5;
// 2D
int** ptr3 = new int*[idx]{};
for (size_t i = 0; i < idx; i++)
{
    ptr3[i] = new int[idx]{};
}
for (size_t i = 0; i < idx; i++)
{
    delete[] ptr3[i];
}
delete[] ptr3;


// 3D
int*** ptr4 = new int**[idx]{};
for (size_t i = 0; i < idx; i++)
{
    ptr4[i] = new int*[idx]{};
    for (size_t j = 0; j < idx; j++)
    {
        ptr4[i][j] = new int[idx]{};
    }
}
... skip ...

-----> smart pointer version?

1 个答案:

答案 0 :(得分:0)

可能这是您正在寻找的但我不认为这是实用的。您可以使用矢量矢量或某种其他可以处理多维数组的结构或库。

int main()
{
    unique_ptr<unique_ptr<int[]>[]> ptr(new unique_ptr<int[]>[5] {});

    for (int i = 0; i < 5; i++)
    {
        unique_ptr<int[]> temp_ptr(new int[5]);
        for (int j = 0; j < 5; j++)
            temp_ptr[j] = i*5 + j;
        ptr[i] = move(temp_ptr);
    }


     for (int i = 0; i < 5; i++)
     {
         for (int j = 0; j < 5; j++)
            cout << ptr[i][j] << " ";
        cout << "\n";
     }
}