Search code examples
c++listremove-if

How to properly Use remove_if?


I am attempting to use the remove_if for an array. The array contains objects of songs which contain 2 string properties (artist and title). I have a bool equals operator but have issues with implementation. Below is my Song equals operator:

bool Song::operator==(const Song& s) const 
{
    return (title_ == s.GetTitle() && artist_ == s.GetArtist()) ?  true : false;
}

I have another function which is supposed to remove the song if either title or artist match the parameters passed into it. Then returns the number of songs removed:

unsigned int Playlist::RemoveSongs(const string& title, const string& artist) 
{
    int startSize = songs_.size();
    Song s = Song(title,artist);
    // below are some of the things I've attempted from documentation
    //songs_.remove_if(std::bind2nd(std::ptr_fun(Song::operator()(s))));
    //std::remove_if(songs_.begin(),songs_.end(),s);
    int endSize = songs_.size();
    return startSize - endSize;
}

Solution

  • Try using lambda... Something like below (not tested). Do not forget to use "[=]" to capture out of scope variables.

    std::remove_if(songs_.begin(), 
                       songs_.end(),
                       [=](Song &s){return (title == s.GetTitle() && artist == s.GetArtist()) ;})