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

single and one-dimensional array can be declared as above. How do I declare a two-dimensional or more array as a smart pointer?

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?
3
  • 2
    Don't do that. Use containers. Perhaps find a library implementing some Matrix template container (or implement it). Notice that C++ don't have two-dimensional arrays (but arrays of arrays). Then use a smart pointer to some Matrix, or (if needed) a Matrix of smart pointers. Commented May 16, 2018 at 4:56
  • What's wrong with vector<vector<int>> ? Commented May 16, 2018 at 5:06
  • I simply curious about the smart pointer syntax in the above situation. Anyway, this way was not good. Commented May 16, 2018 at 5:32

1 Answer 1

0

May be this is what you are looking for but I do not think it is practical. You can use vector of vectors instead or some sort of other structures or libraries that can handle multi dimensional arrays.

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";
     }
}
Sign up to request clarification or add additional context in comments.

Comments