Problem sorting a list of pointers
i am trying to sort a list of pointers (in my case each pointer is of type Job) my intention is to sort the jobs by their serial number
void Container::jobSort(list<Job*> &jobs) {
sort(jobs.begin(), jobs.end(), jobSerialCompare);
}
bool Container::jobSerialCompare(const Job *jobA,const Job *jobB) {
return (jobA->getSn()<jobB->getSn());
}
the error i'm getting is :
error: no matching function for call to 'sort(std::_List_iterator<Job*>, std::_List_iterator<Job*>, <unresolved overloaded function type>)'
/usr/include/c++/4.2.1/bits/stl_algo.h:2852: note: candidates are: void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<Job*>, _Compare = bool (Container::*)(const Job*, const Job*)]
make: *** [src/Container.o] Error 1
i managed to solve the error by changing the code as follows :
struct compare {
bool operator()(const Job *jobA, const Job *jobB) { return (jobA->getSn()<jobB->getSn());
}
};
void Container::jobSort(list<Job*> &jobs) {
jobs.sort(compare());
}
no compilation error now but i'm wondering what is wrong with my initial steps, help is appreciated, cheers
EDIT - Thanks a lot for all the help everyone ! all the different answers helped pain开发者_运维知识库t a clearer picture
The error message says it all. You are trying to sort a list with a sort() that expects a random access iterators. List supports only bidirectional iterators, so the stand-alone sort() doesn't work. That's why you must use a specific algorithms for lists: list.sort();
Also others spotted the non-static comparator issue, which is unrelated to the message you've got (but still must be fixed).
In the first case Container::jobSerialCompare
is a member function. You should convert member function to function object with a mem_fun
function in order to use it with sort
. Try to write
#include <functional>
...
void Container::jobSort(list<Job*> &jobs) {
sort(jobs.begin(), jobs.end(), mem_fun(&Container::jobSerialCompare));
}
in your first version the Container::jobSerialCompare
is a member function so it has an implicit first parameter of this
, and so it does not fit to what std::sort()
expects. The way to solve this is either to define the function in the global scope, or to define a functor, i.e. a class with operator()()
, as you did.
EDIT: ... or to use mem_fun
as VinS suggests
精彩评论