Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSet with a Custom Class



  • I was looking for a very simple example of a Custom Class being used in a QSet, and I could not find one anywhere.

    I have eventually worked out this example, and I wanted to share with everyone, and also get feedback in case I did something wrong.

    myclass.h

    #ifndef MYCLASS_H
    #define MYCLASS_H
    
    #include <QObject>
    #include <QDebug>
    
    class MyClass
    {
    public:
        MyClass();
        MyClass(const MyClass &other);
        MyClass &operator=(const MyClass &other);
        bool operator==(const MyClass &other) const;
    
        QString alpha;
        QString beta;
    };
    
    inline uint qHash(const MyClass &key, uint seed){
        return qHash(key.alpha, seed) ^ qHash(key.beta, seed+1);
    }
    
    QDebug operator<<(QDebug dbg, const MyClass &data);
    #endif // MYCLASS_H
    

    myclass.cpp

    #include "myclass.h"
    
    MyClass::MyClass(){
    
    }
    
    MyClass::MyClass(const MyClass &other){
        alpha = other.alpha;
        beta = other.beta;
    }
    
    MyClass& MyClass::operator=(const MyClass &other){
        MyClass *ret = new MyClass();
        ret->alpha = other.alpha;
        ret->beta = other.beta;
        return *ret;
    }
    
    bool MyClass::operator==(const MyClass &other) const{
        return alpha.compare(other.alpha) == 0 && beta.compare(other.beta) == 0;
    }
    
    QDebug operator<<(QDebug dbg, const MyClass &data){
        dbg.nospace() << "MyClass(" << data.alpha << ", " << data.beta << ")";
        return dbg.maybeSpace();
    }
    

    main.cpp

    #include <QCoreApplication>
    #include <QTimer>
    #include <QDebug>
    
    #include "myclass.h"
    
    int main(int argc, char *argv[]){
        QCoreApplication app(argc, argv);
    
        MyClass a;
        MyClass b;
    
        a.alpha = QString("Hello");
        a.beta = QString("World");
        b.alpha = QString("foo");
        b.beta = QString("bar");
    
        QSet<MyClass> set;
        set.insert(a);
        set.insert(b);
    
        qDebug() << set;
    
        QTimer::singleShot(250, &app, &QCoreApplication::quit);
        return app.exec();
    }
    

    output looks like this:

    QSet(MyClass("foo", "bar"), MyClass("Hello", "World"))
    Press <RETURN> to close this window...
    

  • Qt Champions 2017

    Thanks sharing this example. We appreciate your effort. It helps others as well. Enjoy Qt Programming.


Log in to reply