Evgenii Legotckoi
April 7, 2017, 1:22 p.m.

Qt/C++ - Lesson 062. Comparator for sorting QList

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:

  1. (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:

  1. (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:

  1. // The comparator must be a static function,
  2. // Otherwise it will not be possible to pass it as an argument
  3. static bool compare(const QPointF& first, const QPointF& second)
  4. {
  5. if (first.x() < second.x())
  6. {
  7. return true;
  8. }
  9. else if (first.x() > second.x())
  10. {
  11. return false;
  12. }
  13. else
  14. {
  15. if (first.y() < second.y())
  16. {
  17. return true;
  18. }
  19. else
  20. {
  21. return false;
  22. }
  23. }
  24.  
  25. }

Using the comparator

  1. // Create and fill the list
  2. QList<QPointF> pointsList;
  3. pointsList << QPointF(12.4, 15.4)
  4. << QPointF(14.1, 7.5)
  5. << QPointF(7.2, 5.2)
  6. << QPointF(4.2, 18.5)
  7. << QPointF(4.2, 1.2)
  8. << QPointF(-19.5, 12.4)
  9. << QPointF(1.1, 1.2);
  10.  
  11. // Let's check the content of the list
  12. qDebug() << pointsList;
  13.  
  14. // sort
  15. std::sort(pointsList.begin(), pointsList.end(), compare);
  16.  
  17. // check result
  18. qDebug() << pointsList;

The result will be similar to the one that was given at the beginning.

Recommended articles on this topic

By article asked0question(s)

2

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html