开发者

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

开发者 https://www.devze.com 2023-04-08 23:50 出处:网络
I have a vector<int>* arr, which is actually a 2D array. arr =new vector<int> [size]; Is it ok that I just do

I have a vector<int>* arr, which is actually a 2D array.

arr =  new vector<int> [size];

Is it ok that I just do

dele开发者_如何学Cte arr;

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


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.


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.


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!
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号