Skip to main content
gamedev.net
🔒 Locked

iterator trouble

Started by Mike.Popoloski Apr 14, 2006 at 7:02 PM 3 replies 950+ views
Original Post
Mike.Popoloski
Mike.Popoloski
I am having a little trouble with my vector and deleting items from it. For my vector, I am using this: std::vector structs; Now, I want to loop through each member of the vector and erase each one that has a certain member variable set. This is what I have so far:

std::vector<STRUCT*>::iterator i;
for( i = structs.begin(); i != structs.end(); i++ )
{
   if( ( *i )->bShouldBeCleared )
      structs.erase( i );
}

Now, whenever I run this code, my debugger yells at me every time it hits the 4th line, something along the lines of invalid pointer access. Am I able to do what I am doing? I am quite sure that the objects that the vector is pointing to do exist. Thanks
Mike Popoloski | Journal | SlimDX
Fruny
Fruny
erase() invalidates iterators. Once you're erased i, you can't increment it. Use the return value from erase.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
gumpy
gumpy
my last post happens to be an example of erasing elements while iterating through a container.
This space for rent.
jflanglois
jflanglois
Or use std::remove_if/vector::erase:

bool shouldClear( STRUCT *s ) {  return s->bShouldBeCleared();}// ...structs.erase( std::remove_if( structs.begin(), structs.end(), shouldClear ), structs.end() );
[edit] Make sure that you actually delete the pointers if you have newed them. Erasing them from an STL container will not delete them from memory.


jfl.
Mike.Popoloski
Mike.Popoloski
Quote:
erase() invalidates iterators. Once you're erased i, you can't increment it. Use the return value from erase.

Ah! That would be it. Thanks again.
Mike Popoloski | Journal | SlimDX

Topic Locked

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

Sign in to reply to this topic.