#includeint main() { QHash hash; hash.insert(1, "John"); hash.insert(2, "Mary"); hash.insert(3, "Bill"); auto it = hash.constFind(2); if (it != hash.constEnd()) qDebug() << it.key() << "=" << it.value(); // prints "2=Mary" else qDebug() << "Key not found"; return 0; }
#includeIn this example, we create a custom class called Person, which has a name and an age. We then use Person as the key type for a QHash container. Note that we need to define the hash() and operator== methods to make the class compatible with the container. We insert three Person objects into the container and use constFind to search for a specific Person object (Mary, 25 years old). If the key is found, we print its hash value and the corresponding value from the container. The QHash container and the constFind method are part of the Qt library.class Person { public: Person(const QString& name, int age) : name(name), age(age) {} bool operator==(const Person& other) const { return name == other.name && age == other.age; } int hash() const { return qHash(name) ^ age; } private: QString name; int age; }; int main() { QHash hash; hash.insert(Person("John", 30), "John's data"); hash.insert(Person("Mary", 25), "Mary's data"); hash.insert(Person("Bill", 40), "Bill's data"); auto it = hash.constFind(Person("Mary", 25)); if (it != hash.constEnd()) qDebug() << it.key().hash() << "=" << it.value(); // prints hash value and "Mary's data" else qDebug() << "Key not found"; return 0; }