Qt容器(QHash/QMap等)基本学习记录

一、Qt容器的遍历器

Qt 的容器类提供了两种风格的遍历器:Java 风格和 STL 风格。

每一种容器都有两种 Java 风格的遍历器:一种提供只读访问,一种提供读写访问:

容器 只读遍历器 读写遍历器
QList<T>,QQueue<T> QListIterator<T> QMutableListIterator<T>
QLinkedList<T> QLinkedListIterator<T> QMutableLinkedListIterator<T>
QVector<T>,QStack<T> QVectorIterator<T> QMutableVectorIterator<T>
QSet<T> QSetIterator<T> QMutableSetIterator<Key,T>
QMap<Key, T>,QMultiMap<Key, T> QMapIterator<Key,T> QMutableMapIterator<Key,T>
QHash<Key, T>,QMultiHash<Key, T> QHashIterator<Key,T> QMutableHashIterator<Key,T>

STL 风格的遍历器

STL 风格的遍历器从 Qt 2.0 就开始提供。这种遍历器能够兼容 Qt 和 STL 的通用算法,并且为速度进行了优化。同 Java 风格遍历器类似,Qt 也提供了两种 STL 风格的遍历器:一种是只读访问,一种是读写访问。我们推荐尽可能使用只读访问,因为它们要比读写访问的遍历器快一些。

容器 只读遍历器 读写遍历器
QList<T>,QQueue<T> QList<T>::const_iterator QList<T>::iterator
QLinkedList<T> QLinkedList<T>::const_iterator QLinkedList<T>::iterator
QVector<T>,QStack<T> QVector<T>::const_iterator QVector<T>::iterator
QSet<T> QSet<T>::const_iterator QSet<T>::iterator
QMap<Key, T>,QMultiMap<Key, T> QMap<Key, T>::const_iterator QMap<Key, T>::iterator
QHash<Key, T>,QMultiHash<Key, T> QHash<Key, T>::const_iterator QHash<Key, T>::iter

二、QMap和QHash的对比分析
QMap和QHash的接口相同,可直接替换使用,它们之间的差异如下:

(1)、QHash的查找速度明显快于QMap

(2)、QHash占用的存储空间明显多于QMap

(3)、QHash以任意的方式存储元素

(4)、QMap以Key顺序存储元素

(5)、QHash如果使用自定义类型作为主键,QHash的键类型必须提供operator == () 和 qHash(key)函数

(6)、QMap如果使用自定义类型作为主键,QMap的键类型必须提供operator <函数

Copyright @WinkJie
原文地址:https://www.cnblogs.com/WinkJie/p/14798885.html