QHash Class▲
-
Header: QHash
-
qmake: QT += core
-
Group: QHash is part of tools, Implicitly Shared Classes
Detailed Description▲
QHash<Key, T> is one of Qt's generic container classes. It stores (key, value) pairs and provides very fast lookup of the value associated with a key.
QHash provides very similar functionality to QMap. The differences are:
-
QHash provides faster lookups than QMap. (See Algorithmic Complexity for details.)
-
When iterating over a QMap, the items are always sorted by key. With QHash, the items are arbitrarily ordered.
-
The key type of a QMap must provide operator<(). The key type of a QHash must provide operator==() and a global hash function called qHash() (see qHash).
Here's an example QHash with QString keys and int values:
QHash&
lt;QString, int
&
gt; hash;
To insert a (key, value) pair into the hash, you can use operator[]():
hash["one"
] =
1
;
hash["three"
] =
3
;
hash["seven"
] =
7
;
This inserts the following three (key, value) pairs into the QHash: ("one", 1), ("three", 3), and ("seven", 7). Another way to insert items into the hash is to use insert():
hash.insert("twelve"
, 12
);
To look up a value, use operator[]() or value():
int
num1 =
hash["thirteen"
];
int
num2 =
hash.value("thirteen"
);
If there is no item with the specified key in the hash, these functions return a default-constructed value.
If you want to check whether the hash contains a particular key, use contains():
int
timeout =
30
;
if
(hash.contains("TIMEOUT"
))
timeout =
hash.value("TIMEOUT"
);
There is also a value() overload that uses its second argument as a default value if there is no item with the specified key:
int
timeout =
hash.value("TIMEOUT"
, 30
);
In general, we recommend that you use contains() and value() rather than operator[]() for looking up a key in a hash. The reason is that operator[]() silently inserts an item into the hash if no item exists with the same key (unless the hash is const). For example, the following code snippet will create 1000 items in memory:
// WRONG
QHash&
lt;int
, QWidget *&
gt; hash;
...
for
(int
i =
0
; i &
lt; 1000
; ++
i) {
if
(hash[i] ==
okButton)
cout &
lt;&
lt; "Found button at index "
&
lt;&
lt; i &
lt;&
lt; endl;
}
To avoid this problem, replace hash[i] with hash.value(i) in the code above.
Internally, QHash uses a hash table to perform lookups. This hash table automatically grows and shrinks to provide fast lookups without wasting too much memory. You can still control the size of the hash table by calling reserve() if you already know approximately how many items the QHash will contain, but this isn't necessary to obtain good performance. You can also call capacity() to retrieve the hash table's size.
If you want to navigate through all the (key, value) pairs stored in a QHash, you can use an iterator. QHash provides both Java-style iterators (QHashIterator and QMutableHashIterator) and STL-style iterators (QHash::const_iterator and QHash::iterator). Here's how to iterate over a QHash<QString, int> using a Java-style iterator:
QHashIterator&
lt;QString, int
&
gt; i(hash);
while
(i.hasNext()) {
i.next();
cout &
lt;&
lt; i.key() &
lt;&
lt; ": "
&
lt;&
lt; i.value() &
lt;&
lt; endl;
}
Here's the same code, but using an STL-style iterator:
QHash&
lt;QString, int
&
gt;::
const_iterator i =
hash.constBegin();
while
(i !=
hash.constEnd()) {
cout &
lt;&
lt; i.key() &
lt;&
lt; ": "
&
lt;&
lt; i.value() &
lt;&
lt; endl;
++
i;
}
QHash is unordered, so an iterator's sequence cannot be assumed to be predictable. If ordering by key is required, use a QMap.
Normally, a QHash allows only one value per key. If you call insert() with a key that already exists in the QHash, the previous value is erased. For example:
hash.insert("plenty"
, 100
);
hash.insert("plenty"
, 2000
);
// hash.value("plenty") == 2000
However, you can store multiple values per key by using insertMulti() instead of insert() (or using the convenience subclass QMultiHash). If you want to retrieve all the values for a single key, you can use values(const Key &key), which returns a QList<T>:
QList&
lt;int
&
gt; values =
hash.values("plenty"
);
for
(int
i =
0
; i &
lt; values.size(); ++
i)
cout &
lt;&
lt; values.at(i) &
lt;&
lt; endl;
The items that share the same key are available from most recently to least recently inserted. A more efficient approach is to call find() to get the iterator for the first item with a key and iterate from there:
QHash&
lt;QString, int
&
gt;::
iterator i =
hash.find("plenty"
);
while
(i !=
hash.end() &
amp;&
amp; i.key() ==
"plenty"
) {
cout &
lt;&
lt; i.value() &
lt;&
lt; endl;
++
i;
}
If you only need to extract the values from a hash (not the keys), you can also use foreach:
QHash&
lt;QString, int
&
gt; hash;
...
foreach (int
value, hash)
cout &
lt;&
lt; value &
lt;&
lt; endl;
Items can be removed from the hash in several ways. One way is to call remove(); this will remove any item with the given key. Another way is to use QMutableHashIterator::remove(). In addition, you can clear the entire hash using clear().
QHash's key and value data types must be assignable data types. You cannot, for example, store a QWidget as a value; instead, store a QWidget *.
The qHash() hashing function▲
A QHash's key type has additional requirements other than being an assignable data type: it must provide operator==(), and there must also be a qHash() function in the type's namespace that returns a hash value for an argument of the key's type.
The qHash() function computes a numeric value based on a key. It can use any algorithm imaginable, as long as it always returns the same value if given the same argument. In other words, if e1 == e2, then qHash(e1) == qHash(e2) must hold as well. However, to obtain good performance, the qHash() function should attempt to return different hash values for different keys to the largest extent possible.
For a key type K, the qHash function must have one of these signatures:
uint qHash(K key);
uint qHash(const
K &
amp;key);
uint qHash(K key, uint seed);
uint qHash(const
K &
amp;key, uint seed);
The two-arguments overloads take an unsigned integer that should be used to seed the calculation of the hash function. This seed is provided by QHash in order to prevent a family of algorithmic complexity attacks. If both a one-argument and a two-arguments overload are defined for a key type, the latter is used by QHash (note that you can simply define a two-arguments version, and use a default value for the seed parameter).
Here's a partial list of the C++ and Qt types that can serve as keys in a QHash: any integer type (char, unsigned long, etc.), any pointer type, QChar, QString, and QByteArray. For all of these, the <QHash> header defines a qHash() function that computes an adequate hash value. Many other Qt classes also declare a qHash overload for their type; please refer to the documentation of each class.
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 &
amp;name, const
QDate &
amp;dateOfBirth);
...
private
:
QString myName;
QDate myDateOfBirth;
}
;
inline
bool
operator
==
(const
Employee &
amp;e1, const
Employee &
amp;e2)
{
return
e1.name() ==
e2.name()
&
amp;&
amp; e1.dateOfBirth() ==
e2.dateOfBirth();
}
inline
uint qHash(const
Employee &
amp;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.
Note that the implementation of the qHash() overloads offered by Qt may change at any time. You must not rely on the fact that qHash() will give the same results (for the same inputs) across different Qt versions.
Algorithmic complexity attacks▲
All hash tables are vulnerable to a particular class of denial of service attacks, in which the attacker carefully pre-computes a set of different keys that are going to be hashed in the same bucket of a hash table (or even have the very same hash value). The attack aims at getting the worst-case algorithmic behavior (O(n) instead of amortized O(1), see Algorithmic Complexity for the details) when the data is fed into the table.
In order to avoid this worst-case behavior, the calculation of the hash value done by qHash() can be salted by a random seed, that nullifies the attack's extent. This seed is automatically generated by QHash once per process, and then passed by QHash as the second argument of the two-arguments overload of the qHash() function.
This randomization of QHash is enabled by default. Even though programs should never depend on a particular QHash ordering, there may be situations where you temporarily need deterministic behavior, for example for debugging or regression testing. To disable the randomization, define the environment variable QT_HASH_SEED to have the value 0. Alternatively, you can call the qSetGlobalQHashSeed() function with the value 0.
See Also▲
See also QHashIterator, QMutableHashIterator, QMap, QSet
Member Type Documentation▲
QHash::ConstIterator▲
Qt-style synonym for QHash::const_iterator.
QHash::Iterator▲
Qt-style synonym for QHash::iterator.
[since 5.10] QHash::const_key_value_iterator▲
The QMap::const_key_value_iterator typedef provides an STL-style const iterator for QHash and QMultiHash.
QHash::const_key_value_iterator is essentially the same as QHash::const_iterator with the difference that operator*() returns a key/value pair instead of a value.
This typedef was introduced in Qt 5.10.
See Also▲
See also QKeyValueIterator
QHash::difference_type▲
Typedef for ptrdiff_t. Provided for STL compatibility.
QHash::key_type▲
Typedef for Key. Provided for STL compatibility.
[since 5.10] QHash::key_value_iterator▲
The QMap::key_value_iterator typedef provides an STL-style iterator for QHash and QMultiHash.
QHash::key_value_iterator is essentially the same as QHash::iterator with the difference that operator*() returns a key/value pair instead of a value.
This typedef was introduced in Qt 5.10.
See Also▲
See also QKeyValueIterator
QHash::mapped_type▲
Typedef for T. Provided for STL compatibility.
QHash::size_type▲
Typedef for int. Provided for STL compatibility.
Member Function Documentation▲
QHash::QHash()▲
[since 5.2] QHash::QHash(QHash<Key, T> &&other)▲
Move-constructs a QHash instance, making it point at the same object that other was pointing to.
This function was introduced in Qt 5.2.
[default, since 5.1] QHash::QHash(std::initializer_list<std::pair<Key, T>> list)▲
Constructs a hash with a copy of each of the elements in the initializer list list.
This function is only available if the program is being compiled in C++11 mode.
This function was introduced in Qt 5.1.
[default] QHash::QHash(const QHash<Key, T> &other)▲
Constructs a copy of other.
This operation occurs in constant time, because QHash is implicitly shared. This makes returning a QHash from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and this takes