【问题标题】:How to properly Use remove_if?如何正确使用remove_if?
【发布时间】: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 个字符串属性。

标签: c++ list remove-if


【解决方案1】:

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

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

【讨论】:

  • 好的,这将是正确的答案。在出现此错误的情况下我该怎么办,因为我的原始结构没有副本 'Song' 类型的对象无法分配,因为它的复制分配运算符被隐式删除'
  • 然后使用(Song const& s)作为参数。
  • 不要使用常量。就说(Song &s)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2016-12-25
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2020-12-04
相关资源
最近更新 更多