-
need help with vectors
hi,
I'm having some trouble with a vector. I'm at a point where I need to remove and object from the vector and I inconsistently receive the error:
"vector iterator not dereferencable"
Although I'm not sure what the issue is here as I'm not dereferencing the iterator. If I break and debug it goes into the actual vector class and other built in stuff.
Code:
for (vector<Building>::iterator itBuilding = buildings.begin(); itBuilding != buildings.end(); itBuilding++) {
if (itBuilding->isPointInObject(&downPoint)) {
buildings.erase(itBuilding);
break;
}
}
Thanks
-
You are dereferencing the iterator instead of the Building.
Code:
if ((*itBuilding).isPointInObject(&downPoint)) {
-
No, that is legal as roznor did it, the iterator->member is the same as (*iterator).member
I see one issue, the fact that erase() will invalidate the iterator, but I'm not seeing any other issues. Nothing that will give a compile time error.
-
I don't see anything wrong with the code, it should be the same as bithub's example. Is this a run-time error? It is probably saying that you are dereferencing an invalid iterator.
Because of the break statement, I don't see how this could happen with that code.
Without the break, you are erasing from the vector while iterating over it, which invalidates the iterator you are using. You would have to use the return value of erase instead of incrementing the iterator. The typical solution with a loop looks like this:
Code:
vector<Building>::iterator itBuilding = buildings.begin();
while (itBuilding != buildings.end()) {
if (itBuilding->isPointInObject(&downPoint)) {
itBuilding = buildings.erase(itBuilding);
}
else {
++itBuilding;
}
}
But again, the break should avoid those issues, so I don't know what is wrong here.
-
that was my thinking, that the break would avoid this problem, and to be more clear, this is a runtime problem, it compiles fine.
I haven't tested your suggestion yet, I'm not sure if it will yield any different results, I'd imagine the end result assembly will look fairly similar, but I'll try it out tomorrow unless if anyone has some other suggestions.
Thanks
-
When you break into the debugger, you can go back up the call stack to this code and see what the variables are. You can dig around the iterator code to see if it you can tell if it is invalid. You can check the size of the vector.
It is possible that the vector itself is invalid. Is it a member variable of a deleted object? Check to see if it is possible that the vector itself is corrupted at that point in the code.
-
ok, so it turns out it had nothing to do with the vector code above. Using the debugger properly as you suggested I was able to see exactly where it was screwing up. Thanks.