4

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 paint a clearer picture

3 Answers 3

3

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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));

}

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.