前言
QMap和QList都支持 QList<T>::iterator 迭代器
一、初识
#include <QtCore/QCoreApplication>
//
#include <QList>
#include <QMap>
#include <QDebug>
#include <iostream>
#include <QTextCodec>
//
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
//QList容器测试
qDebug() << QObject::tr("QList容器测试");
QList<int> list;
for (int i = 0; i < 10; i++)
{
list.insert(list.end(), i);
}
QList<int>::iterator j;
for (j = list.begin(); j!=list.end(); ++j)
{
qDebug() << (*j);
*j = (*j) * 10;
}
QList<int>::const_iterator cj;
for (cj = list.begin(); cj!=list.end(); ++cj)
{
qDebug() << (*cj);
}
//QMap容器测试
qDebug() << QObject::tr("QMap容器测试");
QMap<QString, QString> map;
map.insert("beijing", "111");
map.insert("shanghai", "021");
map.insert("tianjin", "022");
QMap<QString, QString>::const_iterator ck;
for(ck = map.constBegin(); ck!=map.constEnd(); ck++)
{
qDebug() << ck.key() << " " << ck.value();
}
QMap<QString, QString>::iterator mk;
mk = map.find("beijing");
if (mk != map.end())
{
mk.value() = "010";
}
qDebug() << "";
QMap<QString, QString>::const_iterator nck;
for(nck = map.constBegin(); nck!=map.constEnd(); nck++)
{
qDebug() << nck.key() << " " << nck.value();
}
return a.exec();
}
二、QMap中嵌套QList
(1)一维数组
刚接触QT的QMap比较困惑,看这名字以为是二维数组
因为我把QList当作一维数组来用了,事实上也确实可以,但只当一维数组太浪费了。可参考别的资料
QMap<QString, QList<QString> > panelStatistics;
QList<QString> panelInfo;
panelInfo.push_back("0102");
panelInfo.push_back("1253");
panelInfo.push_back("1256");
panelStatistics.insert("面板1", panelInfo);
QMap<QString, QList<QString> >::iterator it;
for(it = panelStatistics.begin(); it != panelStatistics.end(); ++it)
{
QList<QString> tmp = it.value();
qDebug()<<it.key() <<" "<< tmp[0] <<" "<< tmp[1] <<" "<< tmp[2];
}
(2)二位数组
//在初始化的时候这样
QMap<int, QList<Qstring> > tableDate;
QList<Qstring> tmp;
for(int i = 0; i < 10; i ++)
{
tmp.clear();
tmp.push_back("monday in row" + QString::number(i));
tmp.push_back("tuesday in row" + QString::number(i));
tmp.push_back("wensday in row" + QString::number(i));
tmp.push_back("thursday in row" + QString::number(i));
tmp.push_back("friday in row" + QString::number(i));
tmp.push_back("sateday in row" + QString::number(i));
tmp.push_back("sunday in row" + QString::number(i));
tableDate.insert(i, tmp);
}
//取值可以这样
QList<Qstring> result;
result = tableDate.value(3);
for(int i = 0; i < reslut.length; i ++)
{
qDebug() << result[i] + " ";
}
(3)类数据库
QMapIterator<int, QList<QString> > iter(tableDate);
QList<QString> whatDate;
while(iter.hasNext())
{
iter.next();
if(whatDate = iter.value())
{
qDebug() << whatDate[0];
qDebug() << whatDate[1];
qDebug() << whatDate[2];
qDebug() << whatDate[3];
}
}