I am using compare function to sort QList
and MyClass has n different attribute(s) like address, age, firstname, lastname etc
SortKey is something like this.
typedef QPair<QString, Qt::SortOrder> SortKeyPair;
//pair of attr name (i.e. gender and order of sorting asc|desc)
static bool compare( MyClass *o1, MyClass *o2)
{
//sortKey is global static var.
if (sortKey.second == Qt::AscendingOrder) {
if (o1->dataField(sortKey.first) < o2->dataField(sortKey.first)) return true;
else return false;
} else {
if (o1->dataField(sortKey.first) > o2->dataField(sortKey.first)) return true;
else return false;
}
return false;
}
Sorting by single attr. works fine with qSort.
But I need list sorted with multiple attr. like ‘sort by lastname, then by age, then by gender’
I need a sort function to sort by multiple sortKey (which is not working !)
How can we sort with multiple sort keys?
Is there any data structure available that supports this ? (like map always keep things sorted according to key given)
Just define your predicate in the logical way, using the major key for comparison and using the minor key as a fallback when the major is inconclusive:
or, for the general case: