c++ - 如何正确使用remove_if?
问题描述
我正在尝试将 remove_if 用于数组。该数组包含包含 2 个字符串属性(艺术家和标题)的歌曲对象。我有一个布尔等于运算符,但在实现上有问题。下面是我的 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()) ;})
推荐阅读
- javascript - 在 ReactJS 中使用本地存储
- python - 前馈神经网络输入层的神经元数量
- c++ - 堆排序它不起作用或计算不正确
- c - 在 C 中,结构数组如何在内存中查找
- r - r 根据关键字搜索字符串并检查日期是否在开始日期和结束日期之间
- asp.net - ASP.NET 标识。向 Autofac 注册 UserManager
- codenameone - Codenameone - 当光标聚焦在键盘打开的文本字段上时,会扭曲屏幕
- angular - 将日期数组分配给 ngx-mydatepicker disableDates
- statistics - 排名数据的统计显着性检验
- c# - 在具有不同测试 IP 的多个位置工作