Iterating through a vector error causes an error, but the standard one for a loop does not

I have vectorone that contains pointers to an abstract type Rock:

vector<Rock*> rocks;

If I scroll a vector with an iterator and then try to access an object (not an abstract class that extends Rock) through an iterator, I get the error "EXC_BAD_ACCESS" in Xcode 4:

vector<Rock*>::iterator rockIter;
for (rockIter = rocks.begin(); rockIter != rocks.end(); ++rockIter)
{
  bullet.hit(*(*rockIter));
}

But looping through it usually doesn't seem to be a problem:

for (int i = 0; i < rocks.size(); i++)
{
  bullet.hit(*rocks[i]);
}

The function hit()looks like this:

bool Bullet::hit(Rock & rock)

I thought that *(*rockIter), and *rock[i]will do the same, but it is clear that this is not so. What is different, and how can I pass an object reference in a vector through an iterator, how do I do with *rock[i]?

+5
source share
1 answer

, , , bullet.hit() ? , iterator, , undefined. int , .

, !

+7

All Articles