本页内容

QHash::key_iterator Class

class QHash::key_iterator

QHash::key_iterator 类为QHash 键提供了一个STL风格的const迭代器。更多内容...

公共函数

key_iterator()
QHash<Key, T>::const_iterator base() const
bool operator!=(QHash<Key, T>::key_iterator other) const
const Key &operator*() const
QHash<Key, T>::key_iterator &operator++()
QHash<Key, T>::key_iterator operator++(int)
const Key *operator->() const
bool operator==(QHash<Key, T>::key_iterator other) const

详细说明

QHash::key_iterator 本质上与QHash::const_iterator 相同,区别在于operator*()和operator->()返回的是键而非值。

在大多数情况下,应使用QHash::iterator 和QHash::const_iterator ,您可以通过调用QHash::iterator::key() 轻松访问键:

for (auto it = hash.cbegin(), end = hash.cend(); it != end; ++it) {
    cout << "The key: " << it.key() << endl;
    cout << "The value: " << qPrintable(it.value()) << endl;
    cout << "Also the value: " << qPrintable(*it) << endl;
}

然而,为了实现QHash 的键与 STL 风格算法之间的互操作性,我们需要一种解引用后指向键而非值的迭代器。借助QHash::key_iterator ,我们可以对一组键应用算法,而无需调用QHash::keys()——后者效率较低,因为它需要进行一次QHash 迭代,并分配内存来创建临时对象QList 。

// 低效,keys() 的开销很大
QList<int>keys=hash.keys();
intnumPrimes=std::count_if(keys.cbegin(),keys.cend(),isPrimeNumber);
qDeleteAll(hash2.keys());

// 高效,无需内存分配
intprimeNums=std::count_if(hash.keyBegin(),hash.keyEnd(),isPrimeNumber);
qDeleteAll(hash2.keyBegin(), hash2.keyEnd());

QHash::key_iterator 如果为 const,则无法修改键。

默认的QHash::key_iterator 构造函数会创建一个未初始化的迭代器。您必须使用QHash 函数(如QHash::keyBegin()或QHash::keyEnd())对其进行初始化。

警告: 隐式共享容器的迭代器其行为 与 STL 迭代器并不完全一致。当迭代器在容器上处于活动状态时,应避免复制该容器。有关详细信息,请参阅《隐式共享迭代器问题》。

另请参阅 QHash::const_iterator 和QHash::iterator 。

成员函数文档

[noexcept default] key_iterator::key_iterator()

默认——构造一个key_iterator 的实例。

[noexcept] QHash<Key, T>::const_iterator key_iterator::base() const

返回该 `key_iterator ` 所基于的底层 `const_iterator `。

[noexcept] bool key_iterator::operator!=(QHash<Key, T>::key_iterator other) const

如果other 指向的项与该迭代器不一致,则返回true ;否则返回false 。

另请参阅 operator==()。

[noexcept] const Key &key_iterator::operator*() const

返回当前项的键。

[noexcept] QHash<Key, T>::key_iterator &key_iterator::operator++()

前缀 ++ 运算符(++i )将迭代器向前移动到哈希表中的下一个元素,并返回指向新当前元素的迭代器。

在 `QHash::keyEnd()` 上调用此函数将导致未定义的结果。

[noexcept] QHash<Key, T>::key_iterator key_iterator::operator++(int)

后缀 ++ 运算符(i++ )将迭代器向前移动到哈希表中的下一个元素,并返回指向前一个元素的迭代器。

这是一个重载函数。

[noexcept] const Key *key_iterator::operator->() const

返回指向当前项键的指针。

[noexcept] bool key_iterator::operator==(QHash<Key, T>::key_iterator other) const

如果 `other ` 指向与该迭代器相同的项,则返回 `true `;否则返回 `false`。

另请参阅 operator!=()。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.