Skip to main content
gamedev.net
🔒 Locked

Removing elements from Vector

Started by doogle Dec 15, 2002 at 4:12 AM 5 replies 500+ views
Original Post
doogle
doogle
I have a vector defined as follows: std::vector vec; and I add elements like this: vec.push_back(new SomeClass()); How do I delete an element from the vector? I have tried this: Iterator iter = vec.begin(); vec.erase(iter); But this gives me an access violation sometimes. Do I have to delete the SomeClass object as well? Such as: Iterator iter = vec.begin(); vec.erase(iter); delete (*iter); How should it be done? Thanks
Miserable
Miserable
The ''opposite'' of push_back() is (logically) pop_back(). This limits you to LIFO data management, though (after all, push and pop are stack operations).
HG
HG
The access violation you''re getting is probably when you reach the end of the vector. Remember to put in a check for vector.end()!

If you want to remove all the elements, use clear().

For efficiency''s sake, however, you may want to have a ''deleted'' flag for the items, restrict yourself to pop_back(), or use another storage class - vectors don''t deal well with deletions anywhere except the end.

-Richard
doogle
doogle
ok thanks...
so should I be using vector if I want to delete things from half way through?
Also, do I need to delete the objects as well as pop them?
doogle
doogle
*poke*
risingdragon3
risingdragon3
If you are not holding pointers in your vector, you do not need to delete the item.
Use a list if you are going to be removing items and adding items anywhere in the list often.
for vector I think iterators are invalidated after a remove / erase operation, so make sure you get new iterators after a remove / erase.


-----------------------------
Gamedev for learning.
libGDN for putting it all together.
doogle
doogle
ok thanks risingdragon3.
and yes I am storing pointers in my list.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.