PDA

View Full Version : Sorting a QList containing structured datas



jean
17th December 2008, 18:52
Hi everybody,

I am sorry for posting what is probably a stupid question but I failed to find by myself the answer... sorting a Qlist with qSort() is tricky when the list only contains a single variable. But using a structure, it failed since the qSort() algorithm did not knows which field in the structure is to be sorted. Here is my code :


struct myData{
QString namefile;
int filesize;
};

QList <myData> list;
populatelist();
...

now how to sort list by namefile or filesize ?
I presume I need some pointers, but as newbie, I turn around it unsuccessfully. Thank you for any help.

jpn
17th December 2008, 19:07
See qSort() docs. You have to implement the operator<() or a LessThan function.

yunpeng880
18th December 2008, 07:56
Hi everybody,

I am sorry for posting what is probably a stupid question but I failed to find by myself the answer... sorting a Qlist with qSort() is tricky when the list only contains a single variable. But using a structure, it failed since the qSort() algorithm did not knows which field in the structure is to be sorted. Here is my code :


struct myData{
QString namefile;
int filesize;
};

QList <myData> list;
populatelist();
...

now how to sort list by namefile or filesize ?
I presume I need some pointers, but as newbie, I turn around it unsuccessfully. Thank you for any help.

follow:
myData md;
md.namefile="test";
md.filesize=100;
list.appand(md);

jean
18th December 2008, 09:06
Thank you for replying but none of these answers are usefull:

to JPN : the Trolltech doc for qSort() only treat single variable QList. Operators are presented for performing special sortings.

to yunpeng880 : my problem is not how to store structured datas in a QList class, but how to sort a field from a structured data once it has been stored in a QList.

In any case, thanks for your replies.

jpn
18th December 2008, 12:16
to JPN : the Trolltech doc for qSort() only treat single variable QList. Operators are presented for performing special sortings.
In your case QList deals with myData struct. QList doesn't care at all what the composition of that type. To be able to use qSort(), you need to implement either

1) myData::operator<():


struct myData {
bool operator<(const myData& other) const {
return namefile < other.namefile; // sort by namefile
}
...
};

// usage:
QList<myData> list;
...
qSort(list);


OR

2) a LessThan function which does the sorting instead of using operator<():


bool namefileLessThan(const myData &d1, const myData &d2)
{
return d1.namefile < d2.namefile; // sort by namefile
}

// usage:
QList<myData> list;
...
qSort(list.begin(), list.end(), namefileLessThan);

jean
18th December 2008, 13:58
JP : Thank you very much for your concise and helpfull help. It works and you have teached me something new.
Jean.