Sorting functors and bikinis
I stand up next to a mountain
Originally uploaded by Mark Witton.
Sorting is one of the most common operations done on a data structure and it’s one of the best examples for generic code and C++ templates.
Qt provides a handy qSort() method which comes in different flavours.
One is quite interesting as it allows you to use a custom sort function.
void qSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan)
LessThen is actually a template parameter. I guess most of the times you will just use a pointer to a global function.
The drawbacks are that you cannot pass parameters to the sorting function, unless you use global static variables. And that’s rather ugly.
The solution is rather trivial. In fact, it’s so silly that I don’t know why I’m blogging about it. I suppose I got some blogging-fever. Or maybe it’s because I am to used to functors, but they are quite handy in some situations.
Yes… the smartest among you might have perceived that the solution involves functors.
C++ functors are just classes (or structs) with a custom "()" operator. So you can create an instance of some class, set some member variable to customize the sorting behaviour and pass the object right to qSort:
struct MySortStruct {
MySortStruct(int opt) : options(opt) {}
bool operator()(const MyItem& a, const MyItem& b) const {
// Sorting frenzy!!
return SOMETHING;
}
int options;
};
// ...
QList<MyItem> list = magicList();
MySortStruct lessThan(FourtyTwo);
qSort(list.begin(), list.end(), lessThan);
So, Qt will end up calling the () operator of the MySortStruct instance you have set up to fit your needs.
That’s very silly, I know. But I have no better topic to blog about, except insult our so-called government.
PS: sorry but this damn WordPress won’t allow blank lines or initial whitespace in <code> tags. I told ya PHP and WP suck like hell!!
