1 QMap深度解析
QMap是一个以升序键顺序存储键值对的数据结构:
- QMap原型为class QMap<K, T>模板。
- QMap中的键值对根据Key进行了排序。
- QMap中的Key必须重载operator <。
QMap的注意事项:
- 通过Key获取Value时:
- 当Key存在:返回对应的Value。
- 当Key不存在:返回值类型所对应的“零”值。
- 插入键值对时:
- 当Key存在:更新Value的值。
- 当Key不存在:插入新的键值对。
QMap使用示例1:
QMap使用示例2:
编程实验:QMap使用体验
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QMap>
#include <QMapIterator>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap<QString, int> map;
map.insert("key 2", 2);
map.insert("key 1", 1);
map.insert("key 0", 0);
QList<QString> kList = map.keys();
for(int i=0; i<kList.count(); i++)
{
qDebug() << kList[i];
}
QList<int> vList = map.values();
for(int i=0; i<vList.count(); i++)
{
qDebug() << vList[i];
}
QMapIterator<QString, int> it(map);
while( it.hasNext() )
{
it.next();
qDebug() << it.key() << " : " << it.value();
}
return a.exec();
}
2 QHash深度解析
QHash是Qt中的哈希数据结构:
- QHash原型为class QHash<K, T>模板。
- QHash中的键值对在内部无序排列。
- QHash中的Key类型必须重载operator == 。
- QHash中的Key对象必须重载全局哈希函数qHash()。
QHash使用示例:
编程实验:QHash使用体验
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QHash>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QHash<QString, int> hash;
hash.insert("key 2", 2);
hash.insert("key 1", 1);
hash.insert("key 0", 0);
QList<QString> kList = hash.keys();
for(int i=0; i<kList.count(); i++)
{
qDebug() << kList[i];
}
QList<int> vList = hash.values();
for(int i=0; i<vList.count(); i++)
{
qDebug() << vList[i];
}
hash["key 4"] = 4;
// 下面这种遍历方式也是可以的
/*
QHashIterator<QString, int> it(hash);
while (it.hasNext())
{
it.next();
qDebug() << it.key() << " : " << it.value();
}
*/
QHash<QString, int>::const_iterator i;
for(i=hash.constBegin(); i!=hash.constEnd(); ++i)
{
qDebug() << i.key() << " : " << i.value();
}
return a.exec();
}
3 QMap和QHash对比分析
QMap和QHash的接口相同,可直接替换使用。
不同点如下:
- QHash的查找速度明显快于QMap。
- QHash占用的存储空间明显对于QMap。
- QHash以任意的方式存储元素,QMap以key顺序存储元素。
- QHash的键类型必须提供operator==()和qHash(key)函数,QMap的键类型必须提供operator<()函数。
参考资料: