Zohar Argov
Zohar Argov

Reputation: 155

sorting a list of pointers c++ - no matching function error

I'm trying to sort a list of pointers by a specific parameter of its class, working on it for almost an hour. it gives me error:

/src/ClassifyById.cpp:26:25: error: no matching function for call to
‘std::list<Worker*>::sort(<unresolved overloaded function type>)’

while searching I've found this: Problem sorting a list of pointers

But this is not my case, and I don't understand why my code doesn't work. as far as I know, I can't use functor in this assignment. here's my code:

#include "ClassifyById.h"
#include "Worker.h"
#include <algorithm>

void ClassifyById::classify(list<Worker*> toClassify) {

    toClassify.sort(compare);  //ERROR### 
 }

bool ClassifyById::compare(Worker* a, Worker* b){
    return (a->getId() < b->getId()); 
}

Why doesn't it compile?

Upvotes: 3

Views: 121

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

Your compare() function is a non-static member function which requires three parameters: in addition to the entities you want to compare it also requires the object which is pointed to by this. The trivial fix is to make the member static or turn it into a non-member function entirely.

However, you are better off using a comparator object with an inline function call operator if your objective is to obtain good performance: the call through a function pointer can generally not be inlined while an inline function call operator is trivial to inline.

Upvotes: 1

Related Questions