Skip to main content
GameDev.net gamedev.net
🔒 Locked

vector::erase

Started by Mulligan Apr 28, 2004 at 8:20 PM 3 replies 450+ views
Original Post
Mulligan
Mulligan
I decided to finally learn stl, and im using a vector now. I have a vector of 5 objects, and want to remove the 3rd one, making the vector length 4. Like this: 12345 - origional 1245 - new I think i use vector::erase for this but, whats with all this bloated iterator crap? I dont understand how to make it work. any help would be great. ---------------------------------------------------------

check out these pictures of mine

timmay314
timmay314
To erase an element at an index i, do

vec.erase(vec.begin() + i)
leiavoia
leiavoia
an iterator is a "pointer to an element for an STL structure". It's a thing that acts like a pointer and can be dereferenced like a pointer, but it's not a pointer. got it?

You won't use them so much for vectors, but heavily for other containers. If you wanted to erase an element in the container, you need to have an iterator that points to that element. (not a straight-up pointer)

for instance, v.begin() returns in iter to the very first element. If you wanted to erase an element, you'd need an iter as a param for erasing. So if you wanted to nuke the first element, you could use v.erase( v.begin() ).

If you wanted to nuke the 3rd element there are several ways to do that, but the quick way is mentioned above.



[edited by - leiavoia on April 28, 2004 10:03:11 PM]
Chris Hare
Chris Hare
All this iterator crap??? You are not going to like the STL.


blah blah blah.
Gorg
Gorg
quote:
Original post by Mulligan
whats with all this bloated iterator crap? I dont understand how to make it work.



Iterators are one the nicest abstraction around. They allow you to go through a collection without knowing the underlying structure.

Also, it does not have to be linear like on an array. For example if you have a tree structure, you can make iterator that goes through the tree depth first or breadth first.

If you are making a game and you are doing a trace on what objects get hit by a ray, you could return an iterator that does front to back or another one that does back to front.

Yet the code to loop through the result will look exactly that same even the if collection or the method of iteration changes.

Topic Locked

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

Sign in to reply to this topic.