The problem of sorting a list of pointers

I'm trying to sort a list of pointers (in my case each pointer is of type Job) I intend 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 am 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 resolve this 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()); } 

Compilation error now, but I wonder what is wrong with my initial steps, help is welcome, greetings

EDIT - Thanks so much for helping everyone! all the different answers helped draw a sharper image

+4
source share
3 answers

The error message says it all. You are trying to sort a list using sort (), which expects random access iterators. The list only supports bidirectional iterators, so stand-alone sort () does not work. This is why you should use certain algorithms for lists: list.sort();

Others also noticed a non-static comparator problem that is not related to the message you have (but still needs to be fixed).

+3
source

in your first version, Container::jobSerialCompare is a member function, so it has an implicit first this parameter, and therefore it is not suitable for the expected std::sort() . The way to solve this is to either define a function in the global domain or define a functor, i.e. A class with operator()() , just like you.

EDIT: ... or use mem_fun as VinS suggests

+2
source

In the first case, Container::jobSerialCompare is a member function. You must convert the member function to a function object using the 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)); 

}

+2
source

All Articles