How to use qSort with custom types in QList?

user3545931 picture user3545931 · Oct 23, 2014 · Viewed 9.6k times · Source

I have a problem with sorting a QList containing instances of a struct:

class modelHeuristic
{

    typedef struct {

         QString c;
         QString t;
         double value;
     }Saving;

public:

QList<Saving> list_saving;

#include "klarkeright.h"

klarkeRight::klarkeRight()
{


}
void klarkeRight::Algoritmo_Asimetrico(modelHeuristic *model)
{

    qSort(model->list_saving.begin(), model->list_saving.end());

}

error: invalid operands to binary expression ('const modelHeuristic::Saving' and 'const modelHeuristic::Saving') return (t1 < t2);

Answer

lpapp picture lpapp · Oct 23, 2014

First of all, QtAlgorithms is mostly deprecated and you should not use it. Please use std::sort instead as recommended by the Qt documentation.

Otherwise, you will need to implement the actual comparison functionality as you seem to be working with custom types. Naturally, the generic algorithm cannot know how to compare to custom items like that. That is what the error is trying to indicate.

Then, you will either need to pass that function to the sorting algorithm as the third argument, or name it operator<. I prefer being explicit, especially since then you can restrict your comparison to the class where it is tied to anyway.

Therefore, I would write something like this:

main.cpp

#include <QtAlgorithms>
#include <QString>
#include <QList>

class modelHeuristic
{
    typedef struct {
        QString c;
        QString t;
        double value;
    } Saving;
    public:    
        static bool savingComparison(const Saving &s1, const Saving &s2)
        {
            return s1.value < s2.value; // This is just an example
        }

        QList<Saving> list_saving;
};

int main()
{
    modelHeuristic *model = new modelHeuristic();
    // This is not doing anything useful with an empty list
    // that is constructed, but it shows how to get the theory right!
    // Also, you really wish to use std::sort here instead.
    qSort(model->list_saving.begin(), model->list_saving.end(), modelHeuristic::savingComparison);
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Please refer to the documentation for details.