const_iterator 类
class QHash::const_iterator
QHash::const_iterator 类为 QHash 和 QMultiHash 提供 STL 风格的常量迭代器。更多内容…
公共成员函数
const_iterator(const iterator &other) | |
---|---|
const_iterator() | |
const Key & | key() const |
const T & | value() const |
bool | operator!=(const const_iterator &other) const |
const T & | operator*() const |
const_iterator & | operator++() |
const_iterator | operator++(int) |
const T * | operator->() const |
bool | operator==(const const_iterator &other) const |
详细描述
QHash 同时提供 STL 风格迭代器 和 Java 风格迭代器。STL 风格迭代器更底层,使用更笨拙;同时也稍快一些。对于已经了解 STL 的开发者来说更加熟悉。
QHash<Key, T>::const_iterator 用来遍历 QHash(或 QMultiHash)。如果想在遍历时修改 QHash,必须使用 QHash::iterator。对于非常量 QHash,使用 QHash::const_iterator 通常也是好的编程实践,除非需要在遍历时改变 QHash。const 迭代器稍快一些并可以提高代码可读性。
QHash::const_iterator 的默认构造函数创建一个未初始化的迭代器。必须在开始遍历前使用 QHash::constBegin(),QHash::constEnd() 或 QHash::find() 等 QHash 函数初始化它。下面是一个典型的循环,该循环打印出 map 中的所有键值对:
QHash hash;
hash.insert("January", 1);
hash.insert("February", 2);
...
hash.insert("December", 12);
QHash::const_iterator i;
for (i = hash.constBegin(); i != hash.constEnd(); ++i)
cout << i.key() << ": " << i.value() << Qt::endl;
与通过键的大小有序存储元素的 QMap 不同,QHash 无序存储元素。唯一的保证是共享同一键的元素(通过 QMultiHash 的函数插入)将按照从最新到最早插入值的顺序连续出现。
同一哈希表可以使用多个迭代器。然而,需要注意任何对 QHash 的直接修改都可能完全改变哈希表中存储的元素顺序,因为该操作可能引起 QHash 重新散列其内部数据结构。如果需要长时间持有迭代器,建议使用 QMap 而非 QHash。
警告: 隐式共享容器迭代器的工作方式和 STL 迭代器不完全相同。当容器的迭代器还处于活动状态时,应该避免拷贝容器。更多信息请参阅隐式共享迭代器问题。
另请参阅 QHash::iterator 和 QHashIterator。
成员函数文档
const_iterator::const_iterator(const iterator &other)
构造一个 other 的副本。
const_iterator::const_iterator()
构造一个未初始化的迭代器。
一定不要对未初始化的迭代器调用 key(),value() 和 operator++() 等函数。使用前要用 operator=() 赋值。
另请参阅 QHash::constBegin() 和 QHash::constEnd()。
const Key &const_iterator::key() const
返回当前元素的键。
另请参阅 value()。
const T &const_iterator::value() const
返回当前元素的值。
bool const_iterator::operator!=(const const_iterator &other) const
如果 other 与本迭代器指向的元素不同,返回 true
;否则返回 false
。
另请参阅 operator==()。
const T &const_iterator::operator*() const
返回当前元素的值。
同 value()。
另请参阅 key()。
const_iterator &const_iterator::operator++()
前置 ++ 运算符(++i
)将迭代器向前移动到哈希表中的下一个元素并返回指向新位置元素的迭代器。
对 QHash::end() 调用该函数将导致未定义结果。
另请参阅 operator–()。
const_iterator const_iterator::operator++(int)
这是一个重载函数。
后置 ++ 运算符(i++
)将迭代器向前移动到哈希表中的下一个元素并返回指向旧位置元素的迭代器。
const T *const_iterator::operator->() const
返回指向当前元素值的指针。
另请参阅 value()。
bool const_iterator::operator==(const const_iterator &other) const
如果 other 与本迭代器指向相同的元素,返回 true
;否则返回 false
。
另请参阅 operator!=()。