I am trying to sort my QList based on a QDateTime but I get the following error:
must use '.*' or '->*' to call pointer-to-member function in 'lessThan (...)', e.g. '(... ->* lessThan) (...)'
if (lessThan(*end, *start))
^
Sort function:
bool sortRecord(Record left, Record right){
return left.getArrival().getDate() < right.getArrival().getDate();
}
Function is called like this:
qSort(recordList.begin(), recordList.end(), sortRecord);
Getter and setter of arrival in Record:
void Record::setArrival(Arrival arrival){
this->arrival = arrival;
}
Arrival Record::getArrival(){
return this->arrival;
}
getDate()
function in Arrival:
QDateTime Arrival::getDate(){
QDateTime qDateTime;
QDate qDate;
qDate.setDate(date.getDateYear(), date.getDateMonth(), date.getDateDay());
qDateTime.setDate(qDate);
vector<string> timeS = splitTime(time.getTimeFrom());
QTime qTime;
qTime.setHMS(stoi(timeS[0]), stoi(timeS[1]), 0);
qDateTime.setTime(qTime);
return qDateTime;
}
What is it that I do wrong?
Thanks!
The problem is here:
qSort(recordList.begin(), recordList.end(), sortRecord);
^^^^^^^^^^
You cannot use a non-static member function as the sort function, because a non-static member function needs to be called on some object (to provide the this
pointer). You can't just call member function like a normal function, which is what the compiler error means. If you'd read the whole error message, not just the first line, then it would have told you that it comes from the line above.
Either make the sortRecord
function a non-member function, or make it a static
member function.
Why is it a member function anyway? It doesn't access *this
, or use any private members ... this smells like bad object oriented style, that's not how we do things in C++ (see e.g. How non-member functions increase encapsulation).
Also why does your sortRecord
function copy its arguments instead of using references? (See https://isocpp.org/wiki/faq/references#call-by-reference)
If you want to write everything as a member function and have pass-by-reference semantics then use Java, not C++. Otherwise, stop writing Java code in C++.
Try this function for sorting.
bool sortRecord(const Record& left, const Record& right)
{
return left.getArrival().getDate() < right.getArrival().getDate();
}
And also make sure that getArrival() and getDate() are const methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With