Search code examples
c++findfriend

C++ find_if member variable of another class


So I have a class called Song, and another class Called SongLibrary. The Songlibrary just contains a set of all songs and appropriate methods.

I am currently trying to make a function to search the song library and check if a song has a particular title.

The problem I am having is that the song title is inaccessible from the songlibrary class.

m_songs is the name of the set I am using in songlibrary to store all the songs.

m_title is the member variable for title in Song.cpp

in SongLibrary.cpp

bool SongLibrary::SearchSong(string title)
{
    bool found = false;

    std::find_if(begin(m_songs), end(m_songs),
        [&](Song const& p) 
    { 
        if (p.m_title == title) // error here (m_title is inaccessible)
        {
            found = true;
        }
    });

    return found;

}

I have attempted to make the method a friend of the song class but i am not exactly sure I understand how it works.

EDIT I Fixed the problem using the following

bool SongLibrary::SearchSong(string title)
{
    if (find_if(begin(m_songs), end(m_songs),[&](Song const& p)

    {return p.getTitle() == title;}) != end(m_songs))
    {
        return true;
    }
    return false;

}

Solution

  • If you want to use friend classes, you should make SongLibrary a friend of Song. But I suggest you make a public getter for your Song-title like this:

    const std::string& getTitle() const { return m_title; }