Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a vector in which I stored objects of structures. Now I need to deallocate the memory .
Kindly tell me how?
Posted

Use the erase()[^] method on the items you wish to delete.
 
Share this answer
 
Comments
Legor 23-Oct-12 6:23am    
I allways thought one has to use the erase-remove idiom to really delete something from a vector and not just decreasing the capacity. Is erase() alone really enough?
http://en.wikipedia.org/wiki/Erase-remove_idiom
Richard MacCutchan 23-Oct-12 6:30am    
Quite possible, I have not checked it thoroughly, something to check later. I provided the link to MSDN so OP could do so.
Memory will be released by vector destructor (unless you have stored pointers inside the vector).
If your vector contains just pointers to the objects (since your are telling us the objects are heap allocated) then you have to delete every pointer (make a loop on vector items).
 
Share this answer
 
v2
Comments
newbie@work 23-Oct-12 5:43am    
I am trying to iterate. I am doing something wrong I guess. Please see this
for(it=Vector.begin();it!=Vector.end();it++)
{

delete *it;
Vector.erase(it);

}
CPallini 23-Oct-12 6:02am    
never call vector.erase this way: "Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

This invalidates all iterator and references to position (or first) and its subsequent elements." ( http://www.cplusplus.com/reference/stl/vector/erase/ ).



You should instead write:
for (it=Vector.begin(); it != Vector.end(); it++)
delete *it;
Vector.erase(it.begin(), it.end());

Note that last step (Vector.erase()) is hardly needed, because Vector destructor will care about.
Legor 23-Oct-12 6:23am    
I allways thought one has to use the erase-remove idiom to really delete something from a vector and not just decreasing the capacity. Is erase() alone really enough?
http://en.wikipedia.org/wiki/Erase-remove_idiom
CPallini 23-Oct-12 6:39am    
Nope (at least as far as I know), as stated by the page you linked: "A common programming task is remove all elements that have a certain value or fulfill a certain criterion from a collection."
This is a very special case and you are using first remove for selecting (and moving) the elemens inside the collection and then erase to make sure the elements are really 'removed'. If you don't need (as in the OP case) to selectively remove the elements then you just use erase.
Legor 23-Oct-12 7:06am    
Yes i think you're right about that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900