2016-10-15 20 views
0

我有一个QList<QStringList>名为其中sortme每个QStringList第一QString是作为串中的有效的整数,例如:Qt的4.8:试图QStringList中的第一元件上排序的QList <QStringList>作为整数

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

对于qsort,这是4.8使用而不是std:,我知道我想要一个比较函数。这是我认为我需要写:

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

然后:

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

我失去了一些东西,很显然,因为编译器抱怨“错误:调用“快速排序没有匹配功能(的QList :: iterator,QList :: iterator,'''尽管我试图对QList<QStringList>sortme进行排序。

回答

3

首先,qsort()所要求的函数必须是一个原始函数,而不是任何类的成员。其次,在你的情况下,这个比较函数必须采用QStringList引用而不是QList引用,因为它是你正在比较的QStringLists。

#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(); 
} 
+0

啊,我太亲近了 - 我以为是qstringlist comparitor,但是由于错误信息而改变了它。静态的东西就是我所缺少的东西,我将它从课堂中移出并放回到qstringlist中,并且它工作正常。 – fyngyrz