vector problem with erase()
ok im reading a c++ book called beginning c++ game programming and doing one of the exercises in it which is:
write a program using vectors and iterators that allows a user to maintain a list of his or her favorite games. The program should allow the user to list all game titles, add a game title, and remove a game title.
I finished the code and upon running everything seems to work except one thing. When i try to remove the last game in the list it freezes and has to be ended. Ive tested everything else and that seems to be the only problem and I have no idea why, so if someone could help me I would be very grateful. Don't know if it matters, but im using Dev-C++.
Code:
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
vector<string> favGames;
vector<string> choices;
choices.push_back("add");
choices.push_back("remove");
choices.push_back("end");
vector<string>::const_iterator iter;
string gameTitle;
string choice;
bool cont = true;
cout << "Use this program to make and modify a list of your favorite games.\n";
while(cont==true)
{
if(favGames.empty())
cout << "\nYour list is currently empty.\n";
else // displays list
{
cout << "\nFavorite Game list:\n";
for(iter = favGames.begin(); iter != favGames.end(); ++iter)
cout << *iter << endl;
}
do
{
cout << "\nadd remove or end? ";
cin >> choice;
if(choice == choices[0])
{
cout << "Whats the name of the game to add?\n";
cin >> gameTitle;
favGames.push_back(gameTitle);
break;
}
else if(choice == choices[1])
{
if(favGames.empty())
{
cout << "Your list is already empty.\n";
break;
}
cout << "Whats the name of the game to remove?\n";
cin >> gameTitle;
int pos = 0;
int oldSize = favGames.size();
for(iter = favGames.begin(); iter != favGames.end(); ++iter)
{
if(gameTitle == *iter)
favGames.erase(favGames.begin()+ pos);
++pos;
}
if(oldSize == favGames.size())
cout << "No such game in the list.\n";
break;
}
else if(choice == choices[2])
{
cout << "Goodbye.\n";
cont = false;
break;
}
else
{
cout << "Please choose valid choice";
}
}while(true);
}
system("PAUSE");
return 0;
}