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?
  • 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. – Basile Starynkevitch May 16 '18 at 04:56
  • What's wrong with `vector>` ? – Sid S May 16 '18 at 05:06
  • I simply curious about the smart pointer syntax in the above situation. Anyway, this way was not good. –  May 16 '18 at 05:32

1 Answers1

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";
     }
}
Shadi
  • 1,701
  • 2
  • 14
  • 27