一、介绍
遍历一个容器可以使用迭代器(iterators)来完成,迭代器提供了一个统一的方法来访问容器中的元素。而Qt的容器类提供了两种类型的迭代器:Java风格迭代器和STL风格迭代器
二、Java 类型迭代器
对于每个容器类,有两个 Java 类型迭代器:一个用于只读操作,一个用于读写操作,各个Java 类型的容器类见表 1。
表 1 Java类型的迭代器类
容器类 |
只读迭代器 |
读写迭代器 |
QList<T>, QQueue<T> |
QListItcrator<T> |
QMutableListItcrator<T> |
QLinkedList<T> |
QLinkedListIterator<T> |
QMutableLinkedListIterator<T> |
QVector<T>, QStack<T> |
QVectorllcrator<T> |
QMutableVectorIterator<T> |
QSet<T> |
QSetItcrator<T> |
QMutableSetItcrator<T> |
QMap<Key, T>, QMultiMap<Key, T> |
QMapIterator<Key, T> |
QMutableMapIterator<Key, T> |
QHash<Key, T>, QMultiHash<Key, T> |
QHashIterator<Key, T> |
QMutablcHashlterator<Key, T |
使用,正向遍历
QList<QString> list;
list << "A" << "B" << "C" << "D";
QListIterator<QString> i (list);
while (i.hasNext()) {
qDebug () << i.next ();
}
反向遍历
QList<QString> list;
list << "A" << "B" << "C" << "D";
QListIterator<QString> secondIter(list);
secondIter.toBack(); // 迭代器移动到列表的最后面(最后一个数据项之后)
while (secondIter.hasPrevious()){ // 如果迭代器不是位于列表的最前面,返回true
qDebug() << secondIter.previous(); // 返回前一个数据项,并且迭代器前移一个位置
}
QList移除
QListIterator没有提供从list中插入或移除项的函数,想要实现插入和移除,你必须使用QMutableListIterator。下面举例说明使用QMutableListIterator从QList<int>中移除所有奇数。
QList<int> list{ 1, 129, 250, 300, 25 };
QMutableListIterator<int> i(list);
while (i.hasNext()) {
if (i.next() % 2 != 0) {
i.remove();
}
}
QListIterator<int> second(list);
while (second.hasNext()) {
qDebug() << second.next();
}
QList修改
如果想修改某项的值,我们可以使用setValue(),下面的代码中,我们用128来替换所以大于128的值:
QList<int> list({1, 129, 250, 300, 25});
QMutableListIterator<int> i(list);
while (i.hasNext()) {
if (i.next() > 128) {
i.setValue(128);
}
}
三、 STL类型迭代器
STL 迭代器与 Qt 和 STL 的原生算法兼容,并且进行了速度优化。具体类型见表 4。
容器类 |
只读迭代器 |
读写迭代器 |
QList<T>, QQueue<T> |
QList<T>::const iterator |
QList<T>::iterator |
QLinkedList<T> |
Q1. i nked List<1>: :const_iterator |
QLinkedList<T>::iterator |
QVector<T>, QStack<T> |
QVector<T>::const_ilerator |
QVector<T>::iterator |
QSet<T> |
QSet<T>::const_iterator |
QSet<T>::iterator |
QMap<Key, P> QMultiMap<Kcy, T> |
QMap<Key, T>::const_iterator |
QMap<Key, T>:: iterator |
QHash<Key, T> QMultiHash<Key, T> |
QHash<Key, T>: :const_iterator |
QHash<Key, T>::iterator |
对于每一个容器类,都有两个 STL 类型迭代器:一个用于只读访问,一个用于读写访问。无需修改数据时一定使用只读迭代器,因为它们速度更快。
正向遍历
QList<QString> list;
list << "A" << "B" << "C" << "D";
QList<QString>::const_iterator i;
for (i = list.constBegin(); i != list.constEnd(); ++i){
qDebug() << *i;
}
反向遍历
QList<QString>::reverse_iterator i;
for (i = list.rbegin(); i != list.rend(); ++i){
*i = i->toLower();
}
四、关联容器类的迭代器的用法
对于关联容器类 QMap 和 QHash,迭代器的操作符返回数据项的值。如果想返回键,使用 key() 函数。对应的,用 value() 函数返回一个项的值。
例如,下面的代码将 QMap<QString,int> map 中所有项的键和值输出:
QMap<QString, int> map;
map.insert("Paris",1993);
map.insert("New York",1995);
map.insert("Mexico City",1996);
QMap<QString, int>::const_iterator i;
for (i = map.constBegin(); i != map.constEnd(); ++i)
qDebug () << i.key () << ':' << i.value ();
参考:
Qt迭代器(Java类型和STL类型)详解
Qt容器类之二:迭代器 - 走看看