Qt笔记-自定义QSet,QHash的Key

官方文档已经说得很详细了。

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.

在此我直接总结下,方便查阅。

构造2个内联函数,方便QHash去对比一个是operator == ,一个是qHash(const QString &, uint);

这里要注意2点:

①operator==:这里要注意,判断2个自定义对象是否相等,如果有唯一标识字段,比如主键,就可以直接用那个,如果没有,就在结构体中想想,拿些字段组合可以唯一标识这个结构体;

②qHash(const QString &, uint):生成hash的,同样要传入唯一标识的,上面的例子是用name生成的hash再和出生时间异或。并且const QString &, uint这个函数是Qt的全局函数(从搬砖的角度看意思就是不需要去包QHash的头文件了)。

下面是己的例子,我这个结构体是对应数据库的,id是唯一标识:

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);
}

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/131389841