QT学习笔记(九):遍历容器-迭代器(iterators)

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.setValue("M");                           // 使用setValue()进行赋值
    j.toFront();
    qDebug()<< "the forward is :";
    while (j.hasNext())                        // 正向遍历列表,结果为Q,A,M,N
        qDebug() << j.next();

    return a.exec();
}

运行结果:
在这里插入图片描述
在这里插入图片描述
QMap 迭代器示例:

#include <QCoreApplication>
#include <QMapIterator>
#include <QMutableMapIterator>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    QMap<QString, QString> map;
    map.insert("Paris", "France");
    map.insert("Guatemala City", "Guatemala");
    map.insert("Mexico City", "Mexico");
    map.insert("Moscow", "Russia");
    
    // 创建Map的只读迭代器,将map作为参数
    QMapIterator<QString,QString> i(map);
    while(i.hasNext()) 									// 正向遍历 map
    {
        i.next();
        qDebug() << i.key() << " : " << i.value();
    }
    if(i.findPrevious("Mexico")) 
    {
    	qDebug() << "find 'Mexico'";  					// 向前查找键的值
    }
    
    // 创建Map的读/写迭代器,将map作为参数
    QMutableMapIterator<QString, QString> j(map);
    while (j.hasNext()) 
    {
        if (j.next().key().endsWith("City")) 			// endsWith()是QString类的函数
            j.remove();                      			// 删除含有“City”结尾的键的项目
    }
    while(j.hasPrevious()) 
    {
        j.previous();          							// 现在的键值对为 (paris,France),(Moscow,Russia)
        qDebug() << j.key() << " : " << j.value();
    }
    
    return a.exec();
}

运行结果:
在这里插入图片描述

2、STL风格:

STL 风格迭代器兼容Qt和STL的通用算法,在速度上进行了优化:
在这里插入图片描述
QList 和QMap 综合STL 风格迭代器示例:

#include <QCoreApplication>
#include <QList>
#include <QDebug>
#include <QMap>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    QList<QString> list;
    list << "A" << "B" << "C" << "D";
   
    // 使用读写迭代器
    QList<QString>::iterator i;      					
    qDebug() << "the forward is :";
    for (i = list.begin(); i != list.end(); ++i) 
    {
        *i = (*i).toLower();         					// 使用QString的toLower()函数转换为小写
        qDebug() << *i;              					// 结果为a,b,c,d
    }
    
    qDebug() << "the backward is :";
    while (i != list.begin())
     {
        --i;
        qDebug() << *i;               					// 结果为d,c,b,a
    }
    
    // 使用只读迭代器
    QList<QString>::const_iterator j; 					
    qDebug() << "the forward is :";
    for (j = list.constBegin(); j != list.constEnd(); ++j)
        qDebug() << *j;               					// 结果为a,b,c,d


	// QMap STL 风格迭代器使用
    QMap<QString, int> map;
    map.insert("one",1);
    map.insert("two",2);
    map.insert("three",3);
    QMap<QString, int>::const_iterator p;
    qDebug() << "the forward is :";
    for (p = map.constBegin(); p != map.constEnd(); ++p)
        qDebug() << p.key() << ":" << p.value();		// 结果为(one,1),(three,3),(two,2)

    return a.exec();
}

运行结果:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3、foreach 关键字:

如果你只是想顺序的变量容器中的所以元素,可以使用Qt的foreach关键字。这个关键字是Qt特定的,是使用预处理器实现的。
它的语法是:

foreach(variable, container) statement;

例如,下面的代码说明了怎么使用foreach来迭代QLinkedList:

QLinkedList<QString> list;
  ...
QString str;
foreach (str, list)
	qDebug() << str;

QList 和QMap foreach 遍历示例:

#include <QCoreApplication>
#include <QList>
#include <QMap>
#include <QMultiMap>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    QList<QString> list;
    list.insert(0, "A");
    list.insert(1, "B");
    list.insert(2, "C");
    qDebug() <<"the list is :";
    foreach (QString str, list)				// 从list中获取每一项
     {   
        qDebug() << str;            		// 结果为A,B,C
    }

    QMap<QString,int> map;
    map.insert("first", 1);
    map.insert("second", 2);
    map.insert("third", 3);
    qDebug() << endl << "the map is :";
   
    foreach (QString str, map.keys())   	// 从map中获取每一个键   
        qDebug() << str << " : " << map.value(str); 	
	 // 输出键和对应的值,结果为(first,1),(second,2),(third,3)

    QMultiMap<QString,int> map2;
    map2.insert("first", 1);
    map2.insert("first", 2);
    map2.insert("first", 3);
    map2.insert("second", 2);
    qDebug() << endl << "the map2 is :";
    QList<QString> keys = map2.uniqueKeys();	 			// 返回所有键的列表
    
	
    foreach (QString str, keys) 							// 遍历所有的键
    {            				
        foreach (int i, map2.values(str))    				// 遍历键中所有的值
            qDebug() << str << " : " << i;
    }
    // 结果为(first,3),(first,2),(first,1),(second,2)
    
    return a.exec();
}

运行结果:
在这里插入图片描述

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值