Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator for use with sort

Tags:

c++

visual-c++

I was looking at http://www.cplusplus.com/reference/algorithm/sort/ and want to implement something similar: I defined a function clauseComparator which is like myfunc given in the example in the link provided.

bool QueryEvaluatorPrivate::clauseComparator(QueryClause cl1, QueryClause cl2) {
    int priority1 = clausePriority(cl1), 
        priority2 = clausePriority(cl2);
    return priority1 < priority2;
}

and I used it like:

sort(clauses.begin(), clauses.end(), clauseComparator);

But VS complains:

Error   4   error C3867: 'QueryEvaluatorPrivate::clauseComparator': function call missing argument list; use '&QueryEvaluatorPrivate::clauseComparator' to create a pointer to member   h:\dropbox\sch\cs3202\code\source\query\query evaluator\queryevaluator.cpp  138
Error   5   error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided h:\dropbox\sch\cs3202\code\source\query\query evaluator\queryevaluator.cpp  138

Firstly whats wrong (missing arg list)? I tried following the suggestion given in the error to add & and ended up with

Error   4   error C2276: '&' : illegal operation on bound member function expression    h:\dropbox\sch\cs3202\code\source\query\query evaluator\queryevaluator.cpp  138
Error   5   error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided h:\dropbox\sch\cs3202\code\source\query\query evaluator\queryevaluator.cpp  138

Whats wrong here? In my understanding, it should pass a function pointer which I understand should be accepted by sort too?

like image 900
Jiew Meng Avatar asked Mar 13 '13 12:03

Jiew Meng


2 Answers

You need to make your member function static in order to be accessible by sort. In your class header, please declare it as such:

static bool QueryEvaluatorPrivate::clauseComparator(const QueryClause & cl1, const QueryClause & cl2);

There is no need to use bind, as your comparator most likely (or shouldn't) have any need to access class members.

like image 131
Ed Rowlett-Barbu Avatar answered Oct 17 '22 07:10

Ed Rowlett-Barbu


You can't use member functions for this. Make clauseComparator a free function or a static member function.

Your comparator should also take arguments by const reference.

like image 22
jrok Avatar answered Oct 17 '22 08:10

jrok