[SOLVED] Use qSort on QList<QMap<QString, QString> >
-
Hi Guys,
Is there a way to sort a QList< QMap<, > > using qSort and avoid to do it manually.
I explain myself, I have a QList with a QMap<QString, QString> as a container which is like that:
QList < QMap<QString, QString> >, the Qlist is as follows:"test1", "3"
"test2", "1"
"test3", "2"
"test4", "0"And I want that the sorting result will be as follow:
"test4", "0"
"test2", "1"
"test3", "2"
"test1", "3"So typically it is based on the value of QMap key.
Thx
-
Your example is unclear. Is that a list of single element maps or a list with single map that has 4 items?
When iterating maps are always sorted by key.
To sort the list you would have to provide your own comparison operator for these maps e.g.
@
bool operator<(const QMap<QString, QString> & m1, const QMap<QString, QString> & m2)
{
return //... whatever criterion
}...
QList<QMap<QString, QString>> list;
...
qSort(list); //now it works
@ -
Ok his is a Qlist of 4 QMaps and each Qmap contains :
"test", "1"
"val1", "value"
"val2", "otherValue""test", "0"
"val1", "value"
"val2", "otherValue""test", "3"
"val1", "value"
"val2", "otherValue""test", "2"
"val1", "value"
"val2", "otherValue" -
Same rules apply.
-
yes but where introduce based on your example the :
@
bool operator<(const QMap<QString, QString> & m1, const QMap<QString, QString> & m2)
{
return //... whatever criterion
}
@ -
It's a free standing function. Put it anywhere in the scope visible to the qSort call.
The "clean" thing to do would be to define a type for your list (typedef) and then define that operaor only for that type. That way you won't pollute the code for other lists of the same type. -
I will change this post to solved since I already made the wanted behaviour.