简体   繁体   中英

Sorting objects in C++

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:

bool compareAlbums(const Album& a1,const Album& a2)
{
    if (a1.getArtist() == a2.getArtist()){
        return (a1.getTitle() < a2.getTitle());
    } else {
        return a1.getArtist() < a2.getArtist()
    }
}

You've tried to sort a std::vector using a function that takes pointers as arguments. The comparison function is given references to its arguments, not pointers.

The immediate problem should be fixed simply by taking the comparison function and adjusting it from

bool compare(const Album*, const Album*)

to

bool compare(Album const &, Album const &)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM