[Qt-interest] Simple qSort() question
Stephen Bryant
steve at bawue.de
Thu Jan 13 11:44:12 CET 2011
Hi,
> I have three QStringLists that I would like to sort.
> [...]
Would you consider reorganising your data?
Others have suggested having an intermediate mapping to translate the
required sort order to the order of the data items, but my opinion is
that that will get a bit messy.
At the moment you have what looks to me like one list per column, and
you wish to sort your rows on one column.
I would suggest you store your data as rows, and sort those, keeping
your associated data together.
Two ways spring to mind. One is with existing Qt classes - use a
QStringList for each row (ie: with 3 entries, one per column), and a
QMap< QString, QStringList > to store them - this sorts it for you, but
random access to a specific row number means more work.
The other way is to write a class to hold each row and a lessThan
function for it which compares your sort field, then just use a single
QList< MyRow > and sort it as you are doing now.
In fact, I think it may be this simple:
class MyRow
{
public:
QString a;
QString b;
QString c;
MyRow( const QString & x, const QString & y, const QString & z )
: a(x), b(y), c(z) {};
};
bool rowLessThan( const MyRow & r1, const MyRow & r2 )
{
return r1.a < r2.a; // sorts on first field
}
QList< MyRow > list;
list.append( MyRow( "foo", "bar", "cheese" ) );
...
qSort( list.begin(), list.end(), rowLessThan );
cout << list[0].c << endl;
Caveat emptor: I have not compiled or tested this! :-)
Steve
More information about the Qt-interest-old
mailing list