Removing a string from vector read-in text file.

So im creating a 'movie rental machine' for project purpose, and have come across some problems without any success in solving them.

It is possible for me to add a movie to the vector like this:

1
2
3
4
5
6
  void MovieList::addMovie(Movie movie)
{
    list.push_back(movie);

    sort (list.begin(), list.end());
}


This vector is later saved in a txt file. (not here another .cpp file)

and the problem is when i want to remove a movie, so i have to search through this same read-in vector and search for a movie namn for example 'The Ring' and then remove it from the vector and in the end save it to the txt file.

Which i wrote like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void MovieList::removeMovie(Movie movie)
{

    vector <Movie>::iterator it;

    for (it = list.begin(); it != list.end(); it++)
    {

        if (it->getTitle() ==  title)
        {
           list.erase(it);
        }
    }
}


Apperently this isnt the right way since it doesnt work. Now im wondering what am i missing? Any suggestions?
Using erase invalidates your iterator.

1
2
3
4
5
6
7
8
9
10
11
12
void MovieList::removeMovie(Movie movie)
{
    vector <Movie>::iterator it = list.begin() ;

    while ( it != list.end() )
    {
        if ( it->getTitle() == movie.getTitle() )
            it = list.erase(it) ;
        else
            ++it ;
    }
}


alternately:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct MovieCmp        // could be replaced by a lambda in C++11.
{
    const Movie& movie ;

    MovieCmp(const Movie & m) : movie(m) {}

    bool operator()(const Movie & m) const
    {
        return movie.getTitle() == m.getTitle() ;
    }
};


void MovieList::removeMovie(Movie movie)
{
    list.erase(std::remove_if(list.begin(), list.end(), MovieCmp(movie)), list.end()) ; 
}

Topic archived. No new replies allowed.