Search code examples
c++sortingqstringlist

How can I do a numeric sort of a QStringList in Qt 4.6.2 where QCollator is not available


I have seen examples of a numeric sort of a QStringList using QCollator. Unfortunately, QCollator is not available until Qt 5.2 or later. I am using Qt4.6.2.

My QStringList only contains integers.

Example QStringList values:

20
2
1
3

Expected sorted result:

1
2
3
20

Can anyone provide a simple example C++ source that will provide a numeric sort for a QStringList?


Solution

  • The Qt documentation for QStringList::sort suggests to use a QMap for sorting by arbitrary orders. You can build a map and get the sorted strings, like this:

    QStringList l = QStringList() << "3" << "20" << "2" << "1";
    QMap<int, QString> m;
    for (auto s : l) m[s.toInt()] = s;
    l = QStringList(m.values());