1.简介
Java风格的迭代器从Qt4时被引入,使用上比STL风格迭代器方便很多,但是新能上稍微弱于后者。
2.示例代码
#include <QCoreApplication>
#include <QList>
#include <QListIterator>
#include <QMutableListIterator>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<QString> list;
list << "A" << "B" << "C" << "D";
QListIterator<QString> i(list); // 创建列表的只读迭代器,将list作为参数
qDebug() << "the forward is :";
while (i.hasNext()) // 正向遍历列表,结果为A,B,C,D
qDebug() << i.next();
qDebug() << "the backward is :";
while (i.hasPrevious()) // 反向遍历列表,结果为D,C,B,A
qDebug() << i.previous();
QMutableListIterator<QString> j(list);
j.toBack(); // 返回列表尾部
while (j.hasPrevious()) {
QString str = j.previous();
if(str == "B") j.remove(); // 删除项目“B”
}
j.insert("Q"); // 在列表最前面添加项目“Q”
j.toBack();
if(j.hasPrevious()) j.previous() = "N"; // 直接赋值
j.previous();
j.setValue("M"); // 使用setValue()进行赋值
j.toFront();
qDebug()<< "the forward is :";
while (j.hasNext()) // 正向遍历列表,结果为Q,A,M,N
qDebug() << j.next();
return a.exec();
}
执行结果:
3.迭代器的有效位置
4. QListIterator常用API
5. QMutableListIterator常用API
QListIterator没有提供向列表中插入或者删除项目的函数,要完成这些功能,就必须使用QMutableListIterator。这个类增加了insert()
函数来完成插入操作,remove()
函数完成删除操作,setValue()
函数完成设置值操作。
与QListIterator相似,QMutableListIterator提供了toFront()
、toBack()
、hasNext()
、next()
、peekNext()
、hasPrevious()
、previous()
和peekPrevious()
等函数。可以在next()
、peekNext()
、previous()
和peekPrevious()
等函数返回的对象上分别使用key()
和value()
函数来获取键和值。