QMap和QHash自动排序问题及解决方案

 问题

有时候想要获得可以按顺序读写的键值对,此时QMap和QHash并不能够满足我们需求

 测试代码:

    QMap<int,int> map;
    map.insert(7,8);
    map.insert(9,5);
    map.insert(8,7);
    QHash<int,int> hash;
    hash.insert(7,8);
    hash.insert(9,5);
    hash.insert(8,7);

    cout << "QMap<>:" << endl;
    cout << map.keys().at(0) <<"," << map.values().at(0) << endl
         << map.keys().at(1) <<"," << map.values().at(1) << endl
         << map.keys().at(2) <<"," << map.values().at(2) << endl;

    cout << "QHash<>:" << endl;
    cout << hash.keys().at(0) <<"," << hash.values().at(0) << endl
         << hash.keys().at(1) <<"," << hash.values().at(1) << endl
         << hash.keys().at(2) <<"," << hash.values().at(2) << endl;

多次输出:

QMap<>:
7,8
8,7
9,5
QHash<>:
9,5
7,8
8,7
QMap<>:
7,8
8,7
9,5
QHash<>:
8,7
7,8
9,5
QMap<>:
7,8
8,7
9,5
QHash<>:
8,7
9,5
7,8

 可以看到

QMap 按任意顺序插入QMap,重复实验,Qmap都会根据Key自动排序

QHash 按任意顺序插入QHash,重复实验,QHash随机顺序

 解决办法

 采用用QPair,并与QList或者QVector嵌套

QList<QPair<T,T>> 

QVector<QPair<T,T>>

 测试代码:

    QList<QPair<int,int>> listPair;
    listPair.append(make_pair(7,8));
    listPair.append(make_pair(9,5));
    listPair.append(make_pair(8,7));
    QVector<QPair<int,int>> vecPair;
    vecPair.append(make_pair(7,8));
    vecPair.append(make_pair(9,5));
    vecPair.append(make_pair(8,7));

    cout << "QList<QPair<>>:" << endl;
    cout << listPair.at(0).first <<"," << listPair.at(0).second << endl
         << listPair.at(1).first <<"," << listPair.at(1).second << endl
         << listPair.at(2).first <<"," << listPair.at(2).second << endl;

    cout << "QVector<QPair<>>:" << endl;
    cout << vecPair.at(0).first <<"," << vecPair.at(0).second << endl
         << vecPair.at(1).first <<"," << vecPair.at(1).second << endl
         << vecPair.at(2).first <<"," << vecPair.at(2).second << endl;

多次输出:

QList<QPair<>>:
7,8
9,5
8,7
QVector<QPair<>>:
7,8
9,5
8,7
QList<QPair<>>:
7,8
9,5
8,7
QVector<QPair<>>:
7,8
9,5
8,7

 参考链接:

QMap,QHash插入后的显示顺序以及记录插入顺序的数据结构_qhash排序_想飞的兔子呀的博客-CSDN博客

 QPair 的用法_qpair用法_艾米莉亚糖的博客-CSDN博客

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值