QT学习笔记(九):遍历容器-迭代器(iterators)
遍历容器 :
遍历一个容器可以使用迭代器(iterators)完成,迭代器提供一个统一的方法来访问容器中的项目。
迭代器:Jave风格、STL(标准模板库(Standard Template Library))风格;当容器中的数据被修改后或由于调用了non-const成员函数导致其脱离了隐式共享,那么这两种迭代器都会失效。
两者比较:
Jave较STL使用方便,但性能上较弱与后者。
Jave风格迭代器:只读访问、读写访问;
1、Jave风格:
QList 迭代器示例:
#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";
// 创建列表的只读迭代器,将list作为参数
QListIterator<QString> i(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();
// 创建列表的读写迭代器,将list作为参数
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.<