list :: remove_if using()运算符和std :: function

时间:2018-05-18 21:07:47

标签: c++

歌曲和播放列表类的结构:

#ifndef PLAYLIST_H
#define PLAYLIST_H

#include <functional>   // For std::function
#include <string>
#include <list>

 using namespace std;

 extern void SongCallback();

 class Song {
   public:
     explicit Song(const string& title, const string& artist,
     const function<void()> = &SongCallback);
     const string& GetTitle() const;
     const string& GetArtist() const;
     bool operator==(const Song& s) const;
     bool operator()(const Song& s) const;

     static bool CompareTitle(const Song& s1, const Song& s2);
     static bool CompareArtistTitle(const Song& s1, const Song& s2);

private:
 const string title_;
 const string artist_;
 const function<void()> callback_;
};

class Playlist {
public:
    explicit Playlist() {}
    void AddSong(const string& title, const string& artist);
    unsigned int RemoveSongs(const string& title, const string& artist);
    list<Song> PlaylistSortedByTitle() const;
    list<Song> PlaylistSortedByArtistTitle() const;
    unsigned int NumSongs() const;
    unsigned int NumSongs(const string& artist) const;

private:
list<Song> songs_;
};

#endif // PLAYLIST_H

cpp文件实现:

unsigned int Playlist::RemoveSongs(const string& title, const string& artist) {
 if (title == "" && artist == ""){
    unsigned int sz = songs_.size();
    songs_.clear();
    return sz;
}

 unsigned int old_size = songs_.size();
 songs_.remove_if(Song(title, artist));
 unsigned int new_size = songs_.size();
 return (old_size - new_size);

}


bool Song::operator()(const Song& s) const {
  // My code so far but seems not working, and what about callback_ member
  // what should I do for it?
    if ( (this->title_ == s.title_ && this->artist_ == s.artist_) ||
         (this->title_ =="" && this->artist_ == s.artist_) ||
         (this->title_ == s.title_ && this->artist_ == "")
     )
       return true;
    else
       return false;
}

对于Song::operator(),我想执行以下步骤:

1)调用callback_成员字段。

2)检查给定的歌曲是否与此实例的标题&amp;艺术家和    如果是,则返回true,否则返回false。

如果此实例的title_或artist_字段为空(&#34;&#34;),那应该是 被视为通配符(分别匹配s的任何标题和/或艺术家)。 意味着,例如,title =&#34;&#34;删除所有匹配艺术家的歌曲,如果艺术家=&#34;&#34;同样的事情,如果两者都是空的,那么我应该匹配所有。

可以为operator()函数提供任何帮助吗?

0 个答案:

没有答案