Sorting a QList containing structured datas
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 :
Code:
struct myData{
int filesize;
};
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.
Re: Sorting a QList containing structured datas
See qSort() docs. You have to implement the operator<() or a LessThan function.
Re: Sorting a QList containing structured datas
Quote:
Originally Posted by
jean
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 :
Code:
struct myData{
int filesize;
};
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);
Re: Sorting a QList containing structured datas
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.
Re: Sorting a QList containing structured datas
Quote:
Originally Posted by
jean
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<():
Code:
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<():
Code:
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);
Re: Sorting a QList containing structured datas
JP : Thank you very much for your concise and helpfull help. It works and you have teached me something new.
Jean.