Reputation: 1428
I have a vector<int>* arr
, which is actually a 2D array.
arr = new vector<int> [size];
Is it ok that I just do
delete arr;
Will arr[i]
be automatically be deleted, since it is a standard vector?
Upvotes: 4
Views: 1497
Reputation: 500933
Your code is broken. You should be using delete[]
with new[]
:
delete[] arr;
Once you fix this, your code will work correctly.
I have to agree with the commenters that a C-style array of vectors looks a bit crazy. Why not use a vector of vectors instead? That'll take care of memory management for you.
Upvotes: 6
Reputation: 23408
You're allocating an array of vectors there. So you'll need array delete:
delete [] arr;
If you were intending to allocate a vector of 'size' elements, you need:
arr = new vector<int>(size); // don't use array delete for this though!
Upvotes: 2
Reputation: 385405
No, you should be using delete[]
when you used new[]
.
But this is madness. You're using nice happy friendly containers for one dimension, then undoing all the goodness by resorting to manual dynamic allocation for the outer dimension.
Instead, just use a std::vector<std::vector<int> >
, or flatten the two dimensions into a single vector.
Upvotes: 10