QHash 类

template <typename Key, typename T> class QHash

QHash 类是提供基于哈希表的字典的模板类。 更多...

Header: #include <QHash>
CMake: find_package(Qt6 COMPONENTS Core REQUIRED)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

注意: 此类的所有函数 可重入 .

公共类型

公共函数

QHash (InputIterator begin , InputIterator end )
QHash (QHash<Key, T> && other )
QHash (const QHash<Key, T> & other )
QHash (std::initializer_list<std::pair<Key, T> > list )
QHash ()
QHash<Key, T> & operator= (QHash<Key, T> && other )
QHash<Key, T> & operator= (const QHash<Key, T> & other )
~QHash ()
QHash::iterator begin ()
QHash::const_iterator begin () const
qsizetype capacity () const
QHash::const_iterator cbegin () const
QHash::const_iterator cend () const
void clear ()
QHash::const_iterator constBegin () const
QHash::const_iterator constEnd () const
QHash::const_iterator constFind (const Key & key ) const
QHash::const_key_value_iterator constKeyValueBegin () const
QHash::const_key_value_iterator constKeyValueEnd () const
bool contains (const Key & key ) const
qsizetype count (const Key & key ) const
qsizetype count () const
QHash::iterator emplace (const Key & key , Args &&... args )
QHash::iterator emplace (Key && key , Args &&... args )
bool empty () const
QHash::iterator end ()
QHash::const_iterator end () const
QHash::iterator erase (QHash::const_iterator pos )
QHash::iterator find (const Key & key )
QHash::const_iterator find (const Key & key ) const
QHash::iterator insert (const Key & key , const T & value )
void insert (const QHash<Key, T> & other )
bool isEmpty () const
Key key (const T & value , const Key & defaultKey = Key()) const
QHash::key_iterator keyBegin () const
QHash::key_iterator keyEnd () const
QHash::key_value_iterator keyValueBegin ()
QHash::const_key_value_iterator keyValueBegin () const
QHash::key_value_iterator keyValueEnd ()
QHash::const_key_value_iterator keyValueEnd () const
QList<Key> keys () const
QList<Key> keys (const T & value ) const
float load_factor () const
bool remove (const Key & key )
qsizetype removeIf (Predicate pred )
void reserve (qsizetype size )
qsizetype size () const
void squeeze ()
void swap (QHash<Key, T> & other )
T take (const Key & key )
T value (const Key & key , const T & defaultValue = T()) const
QList<T> values () const
QTypeTraits::compare_eq_result<U> operator!= (const QHash<Key, T> & other ) const
QTypeTraits::compare_eq_result<U> operator== (const QHash<Key, T> & other ) const
T & operator[] (const Key & key )
const T operator[] (const Key & key ) const
qsizetype erase_if (QHash<Key, T> & hash , Predicate pred )
int qGlobalQHashSeed ()
size_t qHash (const QOcspResponse & response , size_t seed )
size_t qHash (const QMqttTopicFilter & filter , size_t seed )
size_t qHash (const QStringRef & key , size_t seed )
size_t qHash (const QUrl & url , size_t seed = 0)
size_t qHash (const QSslCertificate & key , size_t seed )
size_t qHash (const QMqttTopicName & name , size_t seed )
size_t qHash (const QDateTime & key , size_t seed = 0)
size_t qHash (QSslEllipticCurve curve , size_t seed )
size_t qHash (QDate key , size_t seed = 0)
size_t qHash (const QSslError & key , size_t seed )
size_t qHash (QTime key , size_t seed = 0)
size_t qHash (const std::pair<T1, T2> & key , size_t seed = 0)
size_t qHash (char key , size_t seed = 0)
size_t qHash (uchar key , size_t seed = 0)
size_t qHash (signed char key , size_t seed = 0)
size_t qHash (ushort key , size_t seed = 0)
size_t qHash (short key , size_t seed = 0)
size_t qHash (uint key , size_t seed = 0)
size_t qHash (int key , size_t seed = 0)
size_t qHash (ulong key , size_t seed = 0)
size_t qHash (long key , size_t seed = 0)
size_t qHash (quint64 key , size_t seed = 0)
size_t qHash (qint64 key , size_t seed = 0)
size_t qHash (char8_t key , size_t seed = 0)
size_t qHash (char16_t key , size_t seed = 0)
size_t qHash (char32_t key , size_t seed = 0)
size_t qHash (wchar_t key , size_t seed = 0)
size_t qHash (float key , size_t seed = 0)
size_t qHash (double key , size_t seed = 0)
size_t qHash (long double key , size_t seed = 0)
size_t qHash (const QChar key , size_t seed = 0)
size_t qHash (const QByteArray & key , size_t seed = 0)
size_t qHash (const QByteArrayView & key , size_t seed = 0)
size_t qHash (const QBitArray & key , size_t seed = 0)
size_t qHash (const QString & key , size_t seed = 0)
size_t qHash (QLatin1String key , size_t seed = 0)
size_t qHash (const T * key , size_t seed = 0)
size_t qHash (std::nullptr_t key , size_t seed = 0)
size_t qHash (const QHash<Key, T> & key , size_t seed = 0)
size_t qHash (QPoint key , size_t seed = 0)
size_t qHash (const QSet<T> & key , size_t seed = 0)
size_t qHash (const QVersionNumber & key , size_t seed = 0)
size_t qHash (const QTypeRevision & key , size_t seed = 0)
size_t qHashBits (const void * p , size_t len , size_t seed = 0)
size_t qHashMulti (size_t seed , const T &... args )
size_t qHashMultiCommutative (size_t seed , const T &... args )
size_t qHashRange (InputIterator first , InputIterator last , size_t seed = 0)
size_t qHashRangeCommutative (InputIterator first , InputIterator last , size_t seed = 0)
void qSetGlobalQHashSeed (int newSeed )
QDataStreamIfHasOStreamOperators<Key, T> operator<< (QDataStream & out , const QHash<Key, T> & hash )
QDataStreamIfHasIStreamOperators<Key, T> operator>> (QDataStream & in , QHash<Key, T> & hash )

详细描述

QHash<Key, T> 是一种 Qt 一般 容器类 。它存储 (键,值) 对,并提供键关联值的非常快速查找。

QHash 提供的功能非常相似 QMap 。差异:

  • QHash provides faster lookups than QMap . (See 算法的复杂性 了解细节。)
  • 当遍历 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 ).

这里是 QHash 范例具有 QString 键和 int 值:

QHash<QString, int> hash;
							

要将 (键,值) 对插入哈希,可以使用 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);
							

要查找值,使用 operator[]() 或 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 默认构造值 .

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 () 和 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<int, QWidget *> hash;
...
for (int i = 0; i < 1000; ++i) {
    if (hash[i] == okButton)
        cout << "Found button at index " << i << Qt::endl;
}
							

要避免此问题,替换 hash[i] with hash.value(i) 在以上代码中。

Internally, QHash uses a hash table to perform lookups. This hash table automatically grows 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.

QHash will not shrink automatically if items are removed from the table. To minimize the memory used by the hash, call squeeze ().

If you want to navigate through all the (key, value) pairs stored in a QHash, you can use an iterator. QHash provides both Java 样式迭代器 ( QHashIterator and QMutableHashIterator ) and STL 样式迭代器 ( QHash::const_iterator and QHash::iterator ). Here's how to iterate over a QHash< QString , int> using a Java-style iterator:

QHashIterator<QString, int> i(hash);
while (i.hasNext()) {
    i.next();
    cout << i.key() << ": " << i.value() << Qt::endl;
}
							

Here's the same code, but using an STL-style iterator:

QHash<QString, int>::const_iterator i = hash.constBegin();
while (i != hash.constEnd()) {
    cout << i.key() << ": " << i.value() << Qt::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 .

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
							

If you need to store multiple entries for the same key in the hash table, use QMultiHash .

If you only need to extract the values from a hash (not the keys), you can also use foreach :

QHash<QString, int> hash;
...
foreach (int value, hash)
    cout << value << Qt::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 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 hashing function that returns a hash value for an argument of the key's type.

The hashing 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 ,那么 hash(e1) == hash(e2) must hold as well. However, to obtain good performance, the hashing function should attempt to return different hash values for different keys to the largest extent possible.

A hashing function for a key type K may be provided in two different ways.

The first way is by having an overload of qHash() in K 's namespace. The qHash() function must have one of these signatures:

size_t qHash(K key);
size_t qHash(const K &key);
size_t qHash(K key, size_t seed);
size_t qHash(const K &key, size_t 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).

The second way to provide a hashing function is by specializing the std::hash class for the key type K , and providing a suitable function call operator for it:

namespace std {
template <> struct hash<K>
{
    // seed is optional
    size_t operator()(const K &key, size_t seed = 0) const;
};
}
							

The seed argument has the same meaning as for qHash() , and may be left out.

This second way allows to reuse the same hash function between QHash and the C++ Standard Library unordered associative containers. If both a qHash() overload and a std::hash specializations are provided for a type, then the qHash() overload is preferred.

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 ,和 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 hash implementation.

The convenience qHashMulti () function can be used to implement qHash () for a custom type, where one usually wants to produce a hash value from multiple fields:

范例:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee
{
public:
    Employee() {}
    Employee(const QString &name, 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 size_t qHash(const Employee &key, size_t seed)
{
    return qHashMulti(seed, key.name(), key.dateOfBirth());
}
#endif // EMPLOYEE_H
							

In the example above, we've relied on Qt's own implementation of qHash () for QString and QDate to give us a hash value for the employee's name and date of birth respectively.

Note that the implementation of the qHash () overloads offered by Qt may change at any time. You 不必 rely on the fact that qHash () will give the same results (for the same inputs) across different Qt versions.

算法复杂性攻击

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 算法的复杂性 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 () 函数。

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.

另请参阅 QHashIterator , QMutableHashIterator , QMap ,和 QSet .

成员类型文档编制

QHash:: ConstIterator

Qt 样式同义词 QHash::const_iterator .

QHash:: Iterator

Qt 样式同义词 QHash::iterator .

[since 5.10] QHash:: const_key_value_iterator

The QHash::const_key_value_iterator typedef provides an STL-style const iterator for QHash .

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.

该 typedef 在 Qt 5.10 引入。

另请参阅 QKeyValueIterator .

[alias] QHash:: difference_type

Typedef for ptrdiff_t. Provided for STL compatibility.

[alias] QHash:: key_type

Typedef for Key. Provided for STL compatibility.

[since 5.10] QHash:: key_value_iterator

The QHash::key_value_iterator typedef provides an STL-style iterator for QHash .

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.

该 typedef 在 Qt 5.10 引入。

另请参阅 QKeyValueIterator .

[alias] QHash:: mapped_type

Typedef for T. Provided for STL compatibility.

[alias] QHash:: size_type

Typedef for int. Provided for STL compatibility.

成员函数文档编制

template <typename Args> QHash::iterator QHash:: emplace ( Key && key , Args &&... args )

template <typename Args> QHash::iterator QHash:: emplace (const Key & key , Args &&... args )

Inserts a new element into the container. This new element is constructed in-place using args as the arguments for its construction.

Returns an iterator pointing to the new element.

[since 5.14] template <typename InputIterator> QHash:: QHash ( InputIterator begin , InputIterator end )

Constructs a hash with a copy of each of the elements in the iterator range [ begin , end ). Either the elements iterated by the range must be objects with first and second data members (like QPair , std::pair , etc.) convertible to Key and to T respectively; or the iterators must have key() and value() member functions, returning a key convertible to Key and a value convertible to T 分别。

该函数在 Qt 5.14 引入。

[since 5.2] QHash:: QHash ( QHash < Key , T > && other )

Move-constructs a QHash instance, making it point at the same object that other 所指向的。

该函数在 Qt 5.2 引入。

QHash:: QHash (const QHash < Key , T > & other )

构造副本为 other .

This operation occurs in constant time , because QHash is 隐式共享 . 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 linear time .

另请参阅 operator= ().

[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 .

该函数在 Qt 5.1 引入。

QHash:: QHash ()

构造空哈希。

另请参阅 clear ().

[since 5.2] QHash < Key , T > &QHash:: operator= ( QHash < Key , T > && other )

移动赋值 other 到此 QHash 实例。

该函数在 Qt 5.2 引入。

QHash < Key , T > &QHash:: operator= (const QHash < Key , T > & other )

赋值 other to this hash and returns a reference to this hash.

QHash:: ~QHash ()

Destroys the hash. References to the values in the hash and all iterators of this hash become invalid.

QHash::iterator QHash:: begin ()

返回 STL 样式迭代器 pointing to the first item in the hash.

另请参阅 constBegin () 和 end ().

QHash::const_iterator QHash:: begin () const

这是重载函数。

qsizetype QHash:: capacity () const

Returns the number of buckets in the QHash 的内部哈希表。

The sole purpose of this function is to provide a means of fine tuning QHash 's memory usage. In general, you will rarely ever need to call this function. If you want to know how many items are in the hash, call size ().

另请参阅 reserve () 和 squeeze ().

[since 5.0] QHash::const_iterator QHash:: cbegin () const

返回常量 STL 样式迭代器 pointing to the first item in the hash.

该函数在 Qt 5.0 引入。

另请参阅 begin () 和 cend ().

[since 5.0] QHash::const_iterator QHash:: cend () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last item in the hash.

该函数在 Qt 5.0 引入。

另请参阅 cbegin () 和 end ().

void QHash:: clear ()

Removes all items from the hash and frees up all memory used by it.

另请参阅 remove ().

QHash::const_iterator QHash:: constBegin () const

返回常量 STL 样式迭代器 pointing to the first item in the hash.

另请参阅 begin () 和 constEnd ().

QHash::const_iterator QHash:: constEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last item in the hash.

另请参阅 constBegin () 和 end ().

QHash::const_iterator QHash:: constFind (const Key & key ) const

Returns an iterator pointing to the item with the key in the hash.

If the hash contains no item with the key , the function returns constEnd ().

另请参阅 find ().

[since 5.10] QHash::const_key_value_iterator QHash:: constKeyValueBegin () const

返回常量 STL 样式迭代器 指向第一哈希条目。

该函数在 Qt 5.10 引入。

另请参阅 keyValueBegin ().

[since 5.10] QHash::const_key_value_iterator QHash:: constKeyValueEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary entry after the last entry in the hash.

该函数在 Qt 5.10 引入。

另请参阅 constKeyValueBegin ().

bool QHash:: contains (const Key & key ) const

返回 true if the hash contains an item with the key ;否则返回 false .

另请参阅 count () 和 QMultiHash::contains ().

qsizetype QHash:: count (const Key & key ) const

Returns the number of items associated with the key .

另请参阅 contains ().

qsizetype QHash:: count () const

这是重载函数。

如同 size ().

bool QHash:: empty () const

此函数是为兼容 STL 而提供的。它相当于 isEmpty (), returning true if the hash is empty; otherwise returns false .

QHash::iterator QHash:: end ()

返回 STL 样式迭代器 pointing to the imaginary item after the last item in the hash.

另请参阅 begin () 和 constEnd ().

QHash::const_iterator QHash:: end () const

这是重载函数。

[since 5.7] QHash::iterator QHash:: erase ( QHash::const_iterator pos )

Removes the (key, value) pair associated with the iterator pos from the hash, and returns an iterator to the next item in the hash.

This function never causes QHash to rehash its internal data structure. This means that it can safely be called while iterating, and won't affect the order of items in the hash. For example:

QHash<QObject *, int> objectHash;
...
QHash<QObject *, int>::iterator i = objectHash.find(obj);
while (i != objectHash.end() && i.key() == obj) {
    if (i.value() == 0) {
        i = objectHash.erase(i);
    } else {
        ++i;
    }
}
							

该函数在 Qt 5.7 引入。

另请参阅 remove (), take (),和 find ().

QHash::iterator QHash:: find (const Key & key )

Returns an iterator pointing to the item with the key in the hash.

If the hash contains no item with the key , the function returns end ().

If the hash contains multiple items with the key , this function returns an iterator that points to the most recently inserted value. The other values are accessible by incrementing the iterator. For example, here's some code that iterates over all the items with the same key:

QHash<QString, int> hash;
...
QHash<QString, int>::const_iterator i = hash.find("HDR");
while (i != hash.end() && i.key() == "HDR") {
    cout << i.value() << Qt::endl;
    ++i;
}
							

另请参阅 value () 和 values ().

QHash::const_iterator QHash:: find (const Key & key ) const

这是重载函数。

QHash::iterator QHash:: insert (const Key & key , const T & value )

Inserts a new item with the key and a value of value .

If there is already an item with the key , that item's value is replaced with value .

[since 5.15] void QHash:: insert (const QHash < Key , T > & other )

Inserts all the items in the other hash into this hash.

If a key is common to both hashes, its value will be replaced with the value stored in other .

注意: other contains multiple entries with the same key then the final value of the key is undefined.

该函数在 Qt 5.15 引入。

bool QHash:: isEmpty () const

返回 true if the hash contains no items; otherwise returns false.

另请参阅 size ().

Key QHash:: key (const T & value , const Key & defaultKey = Key()) const

Returns the first key mapped to value ,或 defaultKey if the hash contains no item mapped to value .

This function can be slow ( linear time ), because QHash 's internal data structure is optimized for fast lookup by key, not by value.

[since 5.6] QHash::key_iterator QHash:: keyBegin () const

返回常量 STL 样式迭代器 pointing to the first key in the hash.

该函数在 Qt 5.6 引入。

另请参阅 keyEnd ().

[since 5.6] QHash::key_iterator QHash:: keyEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary item after the last key in the hash.

该函数在 Qt 5.6 引入。

另请参阅 keyBegin ().

[since 5.10] QHash::key_value_iterator QHash:: keyValueBegin ()

返回 STL 样式迭代器 指向第一哈希条目。

该函数在 Qt 5.10 引入。

另请参阅 keyValueEnd ().

[since 5.10] QHash::const_key_value_iterator QHash:: keyValueBegin () const

返回常量 STL 样式迭代器 指向第一哈希条目。

该函数在 Qt 5.10 引入。

另请参阅 keyValueEnd ().

[since 5.10] QHash::key_value_iterator QHash:: keyValueEnd ()

返回 STL 样式迭代器 pointing to the imaginary entry after the last entry in the hash.

该函数在 Qt 5.10 引入。

另请参阅 keyValueBegin ().

[since 5.10] QHash::const_key_value_iterator QHash:: keyValueEnd () const

返回常量 STL 样式迭代器 pointing to the imaginary entry after the last entry in the hash.

该函数在 Qt 5.10 引入。

另请参阅 keyValueBegin ().

QList < Key > QHash:: keys () const

Returns a list containing all the keys in the hash, in an arbitrary order.

The order is guaranteed to be the same as that used by values ().

This function creates a new list, in linear time . The time and memory use that entails can be avoided by iterating from keyBegin () 到 keyEnd ().

另请参阅 values () 和 key ().

QList < Key > QHash:: keys (const T & value ) const

这是重载函数。

Returns a list containing all the keys associated with value value , in an arbitrary order.

This function can be slow ( linear time ), because QHash 's internal data structure is optimized for fast lookup by key, not by value.

float QHash:: load_factor () const

Returns the current load factor of the QHash 's internal hash table. This is the same as capacity ()/ size (). The implementation used will aim to keep the load factor between 0.25 and 0.5. This avoids having too many hash table collisions that would degrade performance.

Even with a low load factor, the implementation of the hash table has a very low memory overhead.

This method purely exists for diagnostic purposes and you should rarely need to call it yourself.

另请参阅 reserve () 和 squeeze ().

bool QHash:: remove (const Key & key )

Removes the item that has the key from the hash. Returns true if the key exists in the hash and the item has been removed, and false otherwise.

另请参阅 clear () 和 take ().

[since 6.1] template <typename Predicate> qsizetype QHash:: removeIf ( Predicate pred )

Removes all elements for which the predicate pred returns true from the hash.

The function supports predicates which take either an argument of type QHash<Key, T>::iterator , or an argument of type std::pair<const Key &, T &> .

Returns the number of elements removed, if any.

该函数在 Qt 6.1 引入。

另请参阅 clear () 和 take ().

void QHash:: reserve ( qsizetype size )

确保 QHash 's internal hash table has space to store at least size items without having to grow the hash table.

This implies that the hash table will contain at least 2 * size buckets to ensure good performance

This function is useful for code that needs to build a huge hash and wants to avoid repeated reallocation. For example:

QHash<QString, int> hash;
hash.reserve(20000);
for (int i = 0; i < 20000; ++i)
    hash.insert(keys[i], values[i]);
							

Ideally, size should be the maximum number of items expected in the hash. QHash will then choose the smallest possible number of buckets that will allow storing size items in the table without having to grow the internal hash table. If size is an underestimate, the worst that will happen is that the QHash will be a bit slower.

In general, you will rarely ever need to call this function. QHash 's internal hash table automatically grows to provide good performance without wasting too much memory.

另请参阅 squeeze () 和 capacity ().

qsizetype QHash:: size () const

Returns the number of items in the hash.

另请参阅 isEmpty () 和 count ().

void QHash:: squeeze ()

Reduces the size of the QHash 's internal hash table to save memory.

The sole purpose of this function is to provide a means of fine tuning QHash 's memory usage. In general, you will rarely ever need to call this function.

另请参阅 reserve () 和 capacity ().

void QHash:: swap ( QHash < Key , T > & other )

Swaps hash other with this hash. This operation is very fast and never fails.

T QHash:: take (const Key & key )

Removes the item with the key from the hash and returns the value associated with it.

If the item does not exist in the hash, the function simply returns a 默认构造值 .

若不使用返回值, remove () 效率更高。

另请参阅 remove ().

T QHash:: value (const Key & key , const T & defaultValue = T()) const

这是重载函数。

Returns the value associated with the key .

If the hash contains no item with the key , the function returns defaultValue , which is a 默认构造值 if the parameter has not been specified.

QList < T > QHash:: values () const

Returns a list containing all the values in the hash, in an arbitrary order.

The order is guaranteed to be the same as that used by keys ().

This function creates a new list, in linear time . The time and memory use that entails can be avoided by iterating from keyValueBegin () 到 keyValueEnd ().

另请参阅 keys () 和 value ().

template <typename U> QTypeTraits::compare_eq_result < U > QHash:: operator!= (const QHash < Key , T > & other ) const

返回 true if other is not equal to this hash; otherwise returns false .

Two hashes are considered equal if they contain the same (key, value) pairs.

This function requires the value type to implement operator==() .

另请参阅 operator== ().

template <typename U> QTypeTraits::compare_eq_result < U > QHash:: operator== (const QHash < Key , T > & other ) const

返回 true if other is equal to this hash; otherwise returns false.

Two hashes are considered equal if they contain the same (key, value) pairs.

This function requires the value type to implement operator==() .

另请参阅 operator!= ().

T &QHash:: operator[] (const Key & key )

Returns the value associated with the key as a modifiable reference.

If the hash contains no item with the key , the function inserts a 默认构造值 into the hash with the key , and returns a reference to it.

另请参阅 insert () 和 value ().

const T QHash:: operator[] (const Key & key ) const

这是重载函数。

如同 value ().

相关非成员

[since 6.1] template <typename Key, typename T, typename Predicate> qsizetype erase_if ( QHash < Key , T > & hash , Predicate pred )

Removes all elements for which the predicate pred returns true from the hash hash .

The function supports predicates which take either an argument of type QHash<Key, T>::iterator , or an argument of type std::pair<const Key &, T &> .

Returns the number of elements removed, if any.

该函数在 Qt 6.1 引入。

[since 5.6] int qGlobalQHashSeed ()

Returns the current global QHash seed.

The seed is set in any newly created QHash 。见 qHash about how this seed is being used by QHash .

该函数在 Qt 5.6 引入。

另请参阅 qSetGlobalQHashSeed .

[since 5.0] size_t qHash (const QUrl & url , size_t seed = 0)

返回哈希值为 url . If specified, seed is used to initialize the hash.

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash (const QDateTime & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( QDate key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( QTime key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.7] template <typename T1, typename T2> size_t qHash (const std::pair < T1 , T2 > & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

类型 T1 and T2 must be supported by qHash().

该函数在 Qt 5.7 引入。

[since 5.0] size_t qHash ( char key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( uchar key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( signed char key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( ushort key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( short key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( uint key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( int key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( ulong key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( long key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( quint64 key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( qint64 key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 6.0] size_t qHash ( char8_t key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 6.0] size_t qHash ( char16_t key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 6.0] size_t qHash ( char32_t key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 6.0] size_t qHash ( wchar_t key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 5.3] size_t qHash ( float key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.3 引入。

[since 5.3] size_t qHash ( double key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.3 引入。

[since 5.3] size_t qHash ( long double key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.3 引入。

[since 5.0] size_t qHash (const QChar key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash (const QByteArray & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 6.0] size_t qHash (const QByteArrayView & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 5.0] size_t qHash (const QBitArray & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash (const QString & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] size_t qHash ( QLatin1String key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 5.0] template <typename T> size_t qHash (const T * key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.0 引入。

[since 6.0] size_t qHash ( std::nullptr_t key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 5.8] template <typename Key, typename T> size_t qHash (const QHash < Key , T > & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

Type T must be supported by qHash().

该函数在 Qt 5.8 引入。

[since 6.0] size_t qHash ( QPoint key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 5.5] template <typename T> size_t qHash (const QSet < T > & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

The hash value is independent of the order of elements in key , that is, sets that contain the same elements hash to the same value.

该函数在 Qt 5.5 引入。

[since 5.6] size_t qHash (const QVersionNumber & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 5.6 引入。

[since 6.0] size_t qHash (const QTypeRevision & key , size_t seed = 0)

返回哈希值为 key ,使用 seed 进行种子计算。

该函数在 Qt 6.0 引入。

[since 5.4] size_t qHashBits (const void * p , size_t len , size_t seed = 0)

Returns the hash value for the memory block of size len pointed to by p ,使用 seed 进行种子计算。

Use this function only to implement qHash () for your own custom types. For example, here's how you could implement a qHash () overload for std::vector<int>:

inline size_t qHash(const std::vector<int> &key, size_t seed = 0)
{
    if (key.empty())
        return seed;
    else
        return qHashBits(&key.front(), key.size() * sizeof(int), seed);
}
							

This takes advantage of the fact that std::vector lays out its data contiguously. If that is not the case, or the contained type has padding, you should use qHashRange () 代替。

It bears repeating that the implementation of qHashBits() - like the qHash () overloads offered by Qt - may change at any time. You 不必 rely on the fact that qHashBits() will give the same results (for the same inputs) across different Qt versions.

该函数在 Qt 5.4 引入。

另请参阅 qHashRange () 和 qHashRangeCommutative ().

[since 6.0] template <typename T> size_t qHashMulti ( size_t seed , const T &... args )

返回哈希值为 args ,使用 seed to seed the calculation, by successively applying qHash () to each element and combining the hash values into a single one.

Note that the order of the arguments is significant. If order does not matter, use qHashMultiCommutative () instead. If you are hashing raw memory, use qHashBits (); if you are hashing a range, use qHashRange ().

This function is provided as a convenience to implement qHash () for your own custom types. For example, here's how you could implement a qHash () overload for a class Employee :

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee
{
public:
    Employee() {}
    Employee(const QString &name, 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 size_t qHash(const Employee &key, size_t seed)
{
    return qHashMulti(seed, key.name(), key.dateOfBirth());
}
#endif // EMPLOYEE_H
							

该函数在 Qt 6.0 引入。

另请参阅 qHashMultiCommutative and qHashRange .

[since 6.0] template <typename T> size_t qHashMultiCommutative ( size_t seed , const T &... args )

返回哈希值为 args ,使用 seed to seed the calculation, by successively applying qHash () to each element and combining the hash values into a single one.

The order of the arguments is insignificant. If order does matter, use qHashMulti () instead, as it may produce better quality hashing. If you are hashing raw memory, use qHashBits (); if you are hashing a range, use qHashRange ().

This function is provided as a convenience to implement qHash () for your own custom types.

该函数在 Qt 6.0 引入。

另请参阅 qHashMulti and qHashRange .

[since 5.5] template <typename InputIterator> size_t qHashRange ( InputIterator first , InputIterator last , size_t seed = 0)

Returns the hash value for the range [ first , last ), using seed to seed the calculation, by successively applying qHash () to each element and combining the hash values into a single one.

The return value of this function depends on the order of elements in the range. That means that

{0, 1, 2}
							

and

{1, 2, 0}
							

hash to different values. If order does not matter, for example for hash tables, use qHashRangeCommutative () instead. If you are hashing raw memory, use qHashBits ().

Use this function only to implement qHash () for your own custom types. For example, here's how you could implement a qHash () overload for std::vector<int>:

inline size_t qHash(const std::vector<int> &key, size_t seed = 0)
{
    return qHashRange(key.begin(), key.end(), seed);
}
							

It bears repeating that the implementation of qHashRange() - like the qHash () overloads offered by Qt - may change at any time. You 不必 rely on the fact that qHashRange() will give the same results (for the same inputs) across different Qt versions, even if qHash () for the element type would.

该函数在 Qt 5.5 引入。

另请参阅 qHashBits () 和 qHashRangeCommutative ().

[since 5.5] template <typename InputIterator> size_t qHashRangeCommutative ( InputIterator first , InputIterator last , size_t seed = 0)

Returns the hash value for the range [ first , last ), using seed to seed the calculation, by successively applying qHash () to each element and combining the hash values into a single one.

The return value of this function does not depend on the order of elements in the range. That means that

{0, 1, 2}
							

and

{1, 2, 0}
							

hash to the same values. If order matters, for example, for vectors and arrays, use qHashRange () instead. If you are hashing raw memory, use qHashBits ().

Use this function only to implement qHash () for your own custom types. For example, here's how you could implement a qHash () overload for std::unordered_set<int>:

inline size_t qHash(const std::unordered_set<int> &key, size_t seed = 0)
{
    return qHashRangeCommutative(key.begin(), key.end(), seed);
}
							

It bears repeating that the implementation of qHashRangeCommutative() - like the qHash () overloads offered by Qt - may change at any time. You 不必 rely on the fact that qHashRangeCommutative() will give the same results (for the same inputs) across different Qt versions, even if qHash () for the element type would.

该函数在 Qt 5.5 引入。

另请参阅 qHashBits () 和 qHashRange ().

[since 5.6] void qSetGlobalQHashSeed ( int newSeed )

Sets the global QHash seed to newSeed .

Manually setting the global QHash seed value should be done only for testing and debugging purposes, when deterministic and reproducible behavior on a QHash is needed. We discourage to do it in production code as it can make your application susceptible to algorithmic complexity attacks .

From Qt 5.10 and onwards, the only allowed values are 0 and -1. Passing the value -1 will reinitialize the global QHash seed to a random value, while the value of 0 is used to request a stable algorithm for C++ primitive types types (like int ) and string types ( QString , QByteArray ).

The seed is set in any newly created QHash 。见 qHash about how this seed is being used by QHash .

If the environment variable QT_HASH_SEED is set, calling this function will result in a no-op.

该函数在 Qt 5.6 引入。

另请参阅 qGlobalQHashSeed .

template <typename Key, typename T> QDataStreamIfHasOStreamOperators < Key , T > operator<< ( QDataStream & out , const QHash < Key , T > & hash )

Writes the hash hash 到流 out .

This function requires the key and value types to implement operator<<() .

另请参阅 序列化 Qt 数据类型 .

template <typename Key, typename T> QDataStreamIfHasIStreamOperators < Key , T > operator>> ( QDataStream & in , QHash < Key , T > & hash )

Reads a hash from stream in into hash .

This function requires the key and value types to implement operator>>() .

另请参阅 序列化 Qt 数据类型 .