fyngyrz fyngyrz - 1 year ago 297
C++ Question

Qt 4.8: trying to sort QList<QStringList> on 1st element of QStringList as integer

I have a

of which the first
in each
is a valid integer as a string, for example:

exampleQStringList << "5" << "foo" << "bar"

For qsort, which is what 4.8 uses rather than std:, I understand I want a comparison function. Here's what I thought I needed to write:

bool MainWindow::qslLessThan(const QList<QStringList> &v1, const QList<QStringList> &v2)
// here I would get the first element.toInt() and return <

and then:

qSort(sortme.begin(), sortme.end(), qslLessThan);

I am missing something, clearly, as the compiler complains "error: no matching function for call to 'qSort(QList::iterator, QList::iterator, )'" even though I am trying to sort a
is that.

Answer Source

Firstly the function that the qsort() requires must be a raw function and not a member of any class. Secondly this comparison function must take, in your case, QStringList references rather than QList references as it is the QStringLists you are comparing.

#include <QCoreApplication>
#include <QDebug>

bool lessThan( const QStringList& v1, const QStringList& v2 )
    return v1.first() < v2.first();

int main(int argc, char *argv[])
    QCoreApplication a(argc, argv);

    QList<QStringList> sortme;

    QStringList entryOne    = QStringList() << "1" << "foo1" << "bar1";
    QStringList entryTwo    = QStringList() << "2" << "foo2" << "bar2";
    QStringList entryThree  = QStringList() << "3" << "foo3" << "bar3";

    sortme << entryTwo << entryOne << entryThree;

    qSort( sortme.begin(), sortme.end(), lessThan );

    // Print out the list data so we can see that it got sorted ok
    for( int i = 0; i < sortme.size(); i++ )
        QString data = sortme.at( i ).join( "," );
        qDebug() << QString( "Item %1: %2" ).arg( i + 1 ).arg( data );

    return a.exec();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download