简体   繁体   English

如何释放c ++内存向量 <int> * arr?

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

I have a vector<int>* arr , which is actually a 2D array. 我有一个vector<int>* arr ,它实际上是一个2D数组。

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? 是否会自动删除arr[i] ,因为它是标准向量?

No, you should be using delete[] when you used new[] . 不,你在使用delete[]时应该使用delete[] 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. 相反,只需使用std::vector<std::vector<int> > ,或将两个维度展平为单个向量。

Your code is broken. 你的代码坏了。 You should be using delete[] with new[] : 你应该使用delete[]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. 我必须同意评论者的说法,C风格的矢量数组看起来有点疯狂。 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: 如果您打算分配'size'元素的向量,则需要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM