Overload == operators to compare the pointer objects

I have to make an overload== operator to check if I already have a song in my library. This is what I have, but it's not correct. I was thinking maybe the const, is not needed.
1
2
3
4
5
6
7
8
9
  vector<Song*>librarySong.

  bool SongInLibrary::operator==( const SongInLibraru &aSong) const{
         for(int index=0; index<librarySong.size()-1; index++){
               if(librarySong[index] == aSong)
                    return true;
         }
         return false;
 }


Any help would be appreciated!
Last edited on
there's a typo in the method parameter type : SongInLibrary, not SongInLibraru
Also suggest you use std::find
1
2
 #include <algorithm>
if ( std::find(librarySong.begin(), librarySong.end(), aSong) != librarySong.end() );
@gunnerfunner Thanks for the help. I am a bit confused on the find function. It iterates through my vector while comparing my object with all the objects inside the vector. If the aSong object is not equivalent to the librarySong object it will return the the vector.end() (which should be empty?). If it exist, will it return the object pointer?

This is what I have to check if the Song exist in the library.
1
2
3
4
5
6
7
bool SongInLibrary::doesSongExist(Song* aSong){

	if(find(librarySong.begin(), librarySong.end(), aSong) != librarySong.end()){
		return false;
	}
	return true;
}


find returns an iterator to the first element in the range that compares equal to aSong and if aSong is absent in librarySong then it returns an iterator to librarySong.end().
Also notice that any librarySong element is a pointer to Song type that you're trying to compare to a const SonginLibrary type passed by reference, aSong. I have not seen the rest of your declarations but there could be a type mis-match unless there's some inheritance involved. Also you'd have to bear in mind the relationship b/w pointer and reference variables for comparison:
1
2
3
4
5
p: pointer variable;
head: reference variable;
if(p == & head);
//or
if(*p == head); 
Last edited on
@gunnerfunner Alright thanks I think I get the general idea of how std::find works.

What do you mean by type mismatch? My Song class has setters and getters to get the Artist, Album, and Song Name. My SongInLibrary class uses vector<Song*> and one function would check if the Song already exist in the library, because we are not allowed duplicates.
Topic archived. No new replies allowed.