C ++ list delete function help
I am trying to do a simple delete and keep getting errors.
Here is a piece of code for my erasure:
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--, iterMines++)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = onScreen.erase(iterMines);
iterMines--;
}
}
I keep getting the compiler message:
1>c:\users\owner\desktop\bosconian\code\bosconian\environment.cpp(158) : error C2664: 'std::list<_Ty>::_Iterator<_Secure_validation> std::list<_Ty>::erase(std::list<_Ty>::_Iterator<_Secure_validation>)' : cannot convert parameter 1 from 'std::list<_Ty>::_Iterator<_Secure_validation>' to 'std::list<_Ty>::_Iterator<_Secure_validation>'
1> with
1> [
1> _Ty=SpaceObject *,
1> _Secure_validation=true
1> ]
1> and
1> [
1> _Ty=Mine *,
1> _Secure_validation=true
1> ]
1> and
1> [
1> _Ty=SpaceObject *,
1> _Secure_validation=true
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
I am puzzled because I believe I am giving it the correct iterator.
Mine is a subclass of SpaceObject (a second generation subclass that is)
Does it have anything to do with it? And how can I fix this?
source to share
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--, iterMines++)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = onScreen.erase(iterMines);
iterMines--;
}
}
One real problem and one possible solution:
erase
will give you the next iterator after the removed item. So, if you are at the beginning and erased, you will be given a new beginning. If you then shrink the iterator, you shrink it to the beginning. And this is not true. It is best to output iterMines++
to the loop body:
std::list<Mine*>::iterator iterMines = mines.begin();
for(int i = oldSizeOfMines; i >0 ; i--)
{
if(player->distanceFrom(*iterMines) < radiusOfOnScreen)
{
onScreen.push_back(*iterMines);
iterMines = mines.erase(iterMines); // change to mines!!
} else {
++iterMines; // better to use ++it instead of it++
}
}
It's better to use pre-increment for this as you never know what the iterator is doing behind the scenes when it creates a copy of itself. ++it
will return a new iterator, but it++
will return a copy of the iterator before incrementing. I commented on the part where a solution is possible :)
source to share