Qt中的QMap和QHash

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的接口相同,可直接替换使用。

不同点如下:

  1. QHash的查找速度明显快于QMap。
  2. QHash占用的存储空间明显对于QMap。
  3. QHash以任意的方式存储元素,QMap以key顺序存储元素。
  4. QHash的键类型必须提供operator==()和qHash(key)函数,QMap的键类型必须提供operator<()函数。

参考资料:

  1. QT实验分析教程
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值