Qt Notes - Custom QSet, QHash Key

The official documentation has already said it in great detail.

If you want to use other types as the key, make sure that you provide operator==() and a qHash() implementation.

Example:
 #ifndef EMPLOYEE_H
 #define EMPLOYEE_H

 class Employee
 {
 public:
     Employee() {}
     Employee(const QString &name, const QDate &dateOfBirth);
     ...

 private:
     QString myName;
     QDate myDateOfBirth;
 };

 inline bool operator==(const Employee &e1, const Employee &e2)
 {
     return e1.name() == e2.name()
            && e1.dateOfBirth() == e2.dateOfBirth();
 }

 inline uint qHash(const Employee &key, uint seed)
 {
     return qHash(key.name(), seed) ^ key.dateOfBirth().day();
 }

 #endif // EMPLOYEE_H

In the example above, we've relied on Qt's global qHash(const QString &, uint) to give us a hash value for the employee's name, and XOR'ed this with the day they were born to help produce unique hashes for people with the same name.

Here I directly summarize it for easy reference.

Construct 2 inline functions, which is convenient for QHash to compare. One is operator == and the other is qHash(const QString &, uint);

There are 2 points to note here:

①operator==: Pay attention here to judge whether two custom objects are equal. If there is a unique identification field, such as a primary key, you can use that directly. If not, think about it in the structure, and use some field combinations to uniquely identify it. this structure;

②qHash(const QString &, uint): To generate a hash, the unique identifier must also be passed in. The above example is to use the hash generated by name and XOR it with the birth time. And the function const QString &, uint is a global function of Qt (from the perspective of moving bricks, it means that there is no need to package the header file of QHash).

The following is my example. My structure corresponds to the database, and id is the unique identifier:

struct EncounterDB{
    int id;
    QString type;       //F = dead
    QString phase;

    friend QDebug operator << (QDebug os, EncounterDB record){

        os << "EncounterDB(" << record.id << "," << record.type << "," << record.phase << ")";
        return os;
    }
};

inline bool operator == (const AnswerDB &db1, const AnswerDB &db2){

    return db1.id == db2.id;
}

inline uint qHash(const AnswerDB &db, uint seed){

    return qHash(db.id, seed);
}

Guess you like

Origin blog.csdn.net/qq78442761/article/details/131389841