QHash::key_iterator Class

class QHash::key_iterator

QHash::key_iterator 类为QHash 键提供了 STL 风格的常量迭代器。更多

公共函数

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 与 基本相同,不同之处在于 operator*() 和 operator->() 返回的是键值而不是值。QHash::const_iterator

在大多数情况下,应使用QHash::iteratorQHash::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() ,这样做效率很低,因为创建一个临时的QList 需要花费一次QHash 的迭代和内存分配。

// 效率低,keys() 费用高QList<int>keys=hash.keys();intnumPrimes=std::count_if(keys.cbegin(),keys.cend(),isPrimeNumber);qDeleteAll(hash2.keys());

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

QHash::key_iterator 是常量,因此无法修改键值。

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

警告: 隐式共享容器上的迭代器与 STL-迭代器的工作方式并不完全相同。当容器上的迭代器处于活动状态时,应避免复制该容器。更多信息,请阅读隐式共享迭代器问题

另请参阅 QHash::const_iteratorQHash::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!=() 。

© 2025 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.