c++ - 如何正确使用remove_if?

标签 c++ list remove-if

我正在尝试将 remove_if 用于数组。该数组包含歌曲对象,其中包含 2 个字符串属性(艺术家和标题)。我有一个 bool 等于运算符,但在实现方面存在问题。下面是我的 Song 等于运算符:

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

我有另一个函数,如果标题或艺术家与传递给它的参数匹配,它应该删除这首歌。然后返回删除的歌曲数:

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;
}

最佳答案

尝试使用 lambda... 如下所示(未测试)。 不要忘记使用“[=]”来捕获作用域外的变量。

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

关于c++ - 如何正确使用remove_if?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50419418/

相关文章:

c++ - 'HMODULE GetModuleHandleW(LPCWSTR )': cannot convert argument 1 from ' const char *' to ' LPCWSTR'

c++ - 如何测量时间?

python - 将主列表中的相似项目分组并根据分组项目创建新列表

list - 在 QML 中滑动删除

c++ - remove_if 基于带有仿函数的 vector 索引

arrays - (Swift)当条件为真时删除数组中所有元素的最简单方法是什么

vector 元素上的 C++ 调用函数,派生自 vector 的基类

Python 列表到 Pandas 数据框的字典

c++ - remove_if 删除 vector 中的所有内容

c++ - 在 C++ 或 Arduino 中,如何在函数中接受未知类型的参数?