【发布时间】:2018-10-29 08:57:20
【问题描述】:
我正在尝试将 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;
}
【问题讨论】:
-
songs_是什么? -
return cond ? true : false;可以是return cond;。 -
如果标题或艺术家匹配,我有另一个功能应该删除歌曲,但您的
operator==只检查标题和艺术家是否匹配。你也没有真正问过一个问题:你的代码可能有问题,但你没有解释发生了什么。 -
如果你创造价值,
remove似乎比remove_if更合适,后者需要谓词。 -
哦,感谢您对退货声明的了解。 song_ 是一个列表
。 Song 类包含 Artist 和 Title 的 2 个字符串属性。