When working with simple types, you can use standard sorting tools. If you want to sort complex objects, by a set of parameters, then you need to write a special comparator, which will perform a comparison on the required parameters.
Let's write a small comparator that will sort objects of class QPointF . Sorting rules will be simple. First of all, the sorting should be done on the X coordinate, and if the X coordinates are the same, then we sort by the Y coordinate.
That is, before sorting the list can look like this:
(QPointF(12.4,15.4), QPointF(14.1,7.5), QPointF(7.2,5.2), QPointF(4.2,18.5), QPointF(4.2,1.2), QPointF(-19.5,12.4), QPointF(1.1,1.2))
After sorting the list will look like this:
(QPointF(-19.5,12.4), QPointF(1.1,1.2), QPointF(4.2,1.2), QPointF(4.2,18.5), QPointF(7.2,5.2), QPointF(12.4,15.4), QPointF(14.1,7.5))
Comparator
Let us write the comparator as a static function:
// The comparator must be a static function, // Otherwise it will not be possible to pass it as an argument static bool compare(const QPointF& first, const QPointF& second) { if (first.x() < second.x()) { return true; } else if (first.x() > second.x()) { return false; } else { if (first.y() < second.y()) { return true; } else { return false; } } }
Using the comparator
// Create and fill the list QList<QPointF> pointsList; pointsList << QPointF(12.4, 15.4) << QPointF(14.1, 7.5) << QPointF(7.2, 5.2) << QPointF(4.2, 18.5) << QPointF(4.2, 1.2) << QPointF(-19.5, 12.4) << QPointF(1.1, 1.2); // Let's check the content of the list qDebug() << pointsList; // sort std::sort(pointsList.begin(), pointsList.end(), compare); // check result qDebug() << pointsList;
The result will be similar to the one that was given at the beginning.