How to free C ++ <int> * arr memory vector?

I have a vector<int>* arr , which is actually a two-dimensional array.

 arr = new vector<int> [size]; 

Ok what am i just doing

 delete arr; 

Will arr[i] be deleted automatically, since this is a standard vector?

+4
source share
3 answers

No, you should use delete[] when you used new[] .

But this is crazy. You use nice, friendly containers for one dimension, and then destroy all goodness by resorting to manual dynamic allocation for the outer dimension.

Instead, simply use std::vector<std::vector<int> > or smooth two dimensions into one vector.

+10
source

Your code does not work. You should use delete[] with new[] :

 delete[] arr; 

Once you fix this, your code will work correctly.

I have to agree with commentators that the array of C-style vectors looks a little crazy. Why not use a vector of vectors instead? This will help you in memory management.

+6
source

You select an array of vectors there. Therefore, you will need to remove the array:

 delete [] arr; 

If you intended to highlight the element vector 'size', you need:

 arr = new vector<int>(size); // don't use array delete for this though! 
+2
source

All Articles