View Full Version : Sort QList of pointers
giantdragon
1st June 2011, 15:28
I have a QList of QTcpSocket derived class pointers, which have a custom field for transfer speed and I need to sort list by this field. It is easy to use function qSort for list of values, but I haven't found how not apply this func for list of pointers.
joyer83
1st June 2011, 16:53
Maybe you could use this version of the qSort?
void qSort ( RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan )
And use your own less than comparison function where you compare the fields.
giantdragon
1st June 2011, 19:05
Maybe you could use this version of the qSort?
void qSort ( RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan )
And use your own less than comparison function where you compare the fields.
I know about this method, but I don't know how to correctly write this function for accepting pointers.
bool lessThan(MyClass *first, MyClass *second)
Doesn't work.
wysota
1st June 2011, 19:41
Seems to work fine for me:
#include <QtCore>
struct A {
A(int _x) : x(_x){}
int x;
};
bool lessThan(A *one, A*two){
return one->x < two->x;
}
int main(int argc, char **argv){
QList<A*> list;
for(int i=0;i<100;++i){
list << new A(qrand()%1000);
}
qSort(list.begin(), list.end(), lessThan);
foreach(A *it, list) qDebug() << it->x;
return 0;
}
giantdragon
1st June 2011, 20:32
Finally I found solution: just need to add STATIC keyword to function's declaration, e.g. for descending sort:
Header:
static bool compareSockets(ClientSocket *first, ClientSocket *second);
CPP:
bool NetworkManager::compareSockets(ClientSocket *first, ClientSocket *second)
{
return first->getTransferSpeed() > second->getTransferSpeed();
}
Call:
qSort(clientList->begin(), clientList->end(), compareSockets);
wysota
1st June 2011, 20:53
Finally I found solution: just need to add STATIC keyword to function's declaration
It's a method not a function. That's your problem -- lessThan is supposed to be a function.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.