Reputation: 3799
I've got a pretty simple class with a vector as a private variable like so:
#include "Zombie.h"
#include <vector>
class CGame{
public:
CGame();
void DoVectorStuff();
private:
std::vector<Zombie> zombies;
};
In the function DoVectorStuff() im just looping through the vector like so:
for(std::vector<Zombie>::iterator it = zombies.begin(); it != zombies.end(); ++it)
{
it->Update(delta);
}
Which is causing Visual Studio 2010 to give me a debug assertion when I run it. The same code worked fine when it was in a function by itself, I assume its something to do with me adding it to a class but I can't figure out what.
EDIT: https://i.sstatic.net/2K9GY.png This is the error I'm getting.
Upvotes: 1
Views: 2177
Reputation: 168616
Wild Guess: Zombie::Update
updates, among other things, the zombies
vector, invalidating the iterator it
. Do zombies die or reproduce during their Update
cycle?
Upvotes: 1
Reputation: 24403
The assertion you are getting vector iterators imcompatible indicates that you are trying to compare iterators from different vectors.
Typically you can get these by
POSSIBILITY 1
std::vector<int> foo( 100 );
std::vector<int> bar( 100 );
for( std::vector<int>::iterator iter = foo.begin();
iter != bar.end();
++iter )
{
std::cout << *iter;
}
Notice the above code and you will notice that I am comparing iter that is a iterator from foo vector
to bar.end()
POSSIBILITY 2
Another way you can get the same error is by hanging on to invalid iterators.
std::vector<int> foo( 3 );
std::vector<int>::iterator enditer = foo.end();
foo.push_back( 3 );
foo.push_back( 3 );
foo.push_back( 3 ); // can invalidate endIter above
for( std::vector<int>::iterator iter = foo.begin();
iter != enditer;
++iter )
{
std::cout << *iter;
}
Notice how in the above code I have hanged on to endIter which can be invalidated by adding more elements to foo
Upvotes: 2
Reputation: 2277
Try to use
std::vector<Zombie>::iterator
instead of
std::vector::iterator
Upvotes: 0