PDA

View Full Version : Sorting a QStringlist issue



George Neil
29th September 2009, 12:11
I tried the following code,

QStringList oStrlist;
oStrlist << "A_1" << "A_2" << "A_3" << "A_10" << "A_11";
oStrlist.sort();

This gives me a result like
A_1, A_10, A_11, A_2, A_3.

I need A_10, A_11 to come only after A_2, A_3. Is there any way to do this.

yogeshgokul
29th September 2009, 12:36
I tried the following code,
QStringList oStrlist;
oStrlist << "A_1" << "A_2" << "A_3" << "A_10" << "A_11";
oStrlist.sort();
This gives me a result like
A_1, A_10, A_11, A_2, A_3.
I need A_10, A_11 to come only after A_2, A_3. Is there any way to do this.
According to you, the list is sorted already ;)
You can always do custom sorting. Click here (http://doc.trolltech.com/4.5/qtalgorithms.html) for more info.

faldzip
29th September 2009, 12:52
As yogeshgokul said the list is sorted well (lexicographically). The sorting you want you can achieve with custom comparator and use it with qSort():


struct MyLessThan {
bool operator()(const QString &s1, const QString &s2) const {
QString st1 = s1.left(s1.indexOf('_'));
int it1 = s1.right(s1.size() - s1.indexOf('_') - 1).toInt();
QString st2 = s2.left(s2.indexOf('_'));
int it2 = s2.right(s2.size() - s2.indexOf('_') - 1).toInt();
if (st1 < st2)
return true;
if (st1 > st2)
return false;
if (it1 < it2)
return true;
return false;
}
};

than you can use it like this:


QStringList slist;
slist << "A_8" << "A_2" << "A_10" << "A_24" << "A_1";
MyLessThan le;
qSort(slist.begin(), slist.end(), le);
foreach (const QString &str, slist) {
ui->plainTextEdit->appendPlainText(str);
}

that gives me output:


A_1
A_2
A_8
A_10
A_24

yogeshgokul
29th September 2009, 13:05
As yogeshgokul said the list is sorted well (lexicographically).

See his input itself sorted :D


QStringList oStrlist;
oStrlist << "A_1" << "A_2" << "A_3" << "A_10" << "A_11";
oStrlist.sort();


@Falzip
Nice phrase
lexicographically

George Neil
30th September 2009, 05:23
Great....that works...!!