0

iterators and erase function

I am going though "Learn C++ through game programming." It has asked me to create a program that will allow a user to maintain a list of games. The user should be able to view the list. Add and remove from the list. Ect. I have managed to get it working well with one exception. I set myIterator=find(inventory.begin(),inventory.end(),eradicate) with eradicate being the variable representing the game they want to remove. It does remove the game they select however if they were to type a game that is not actually on the list then this still removes the last game from the list. I believe this is bc if it does not find anything then the iterator lands on the last item on the list and is set to that. Does anyone have any idea on how to rectify this?

14th Jun 2017, 10:22 PM
Bryan
1 Antwort
0
find returns the iterator if it finds something, but if it does not it return the end iterator. You can compare if the iterator is not equal to this and only then erase like: if(myIterator != inventory.end()) { inventory.erase(myIterator); } Also note that the end points to 1 past the last element.
14th Jun 2017, 10:43 PM
Dennis
Dennis - avatar