I have a really strange error when I try and sort objects using a compare method in C++
required from 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Album*, std::vector<Album> >; _Compare = bool (*)(const Album*, const Album*)]'
It doesn’t seem to be a standard error, but I can’t see anything wrong with my code. Is it a problem with the compare method, or the sort itself. Any help would be greatly appreciated.
I have attached the relevant code:
Album.cpp: http://pastebin.com/0tNrbdrT
Album.h: http://pastebin.com/iY2Yy7qM
AlbumCollection.cpp: http://pastebin.com/gWj0nS8S
AlbumCollection.h: http://pastebin.com/bFrxme5n
AlbumCollection Sort:
void AlbumCollection::sortAlbums(){
std::sort(albums.begin(), albums.end(), compareAlbums);
}
Album compare method:
bool Album::compareAlbums(const Album* a1,const Album* a2)
{
if (a1->getArtist() == a2->getArtist()){
return (a1->getTitle() < a2->getTitle());
}else{
return a1->getArtist() < a2->getArtist()
}
}
The error is: http://pastebin.com/PeXk0FUT
I’m not sure how much is relevant, I’m quite new to C++
There are two errors here. First, the compareAlbums function needs to be a free function, not a member function of the Album class. Second, the compareAlbums function must take const-references to Album objects, since that is what you store in your vector. So, this should fix it: