从嵌套QMAP中获得价值

Getting Value out of Nested QMap

本文关键字:嵌套 QMAP      更新时间:2023-10-16

我有一个嵌套的qmap QMap <QString, QMap<QString, QVariant> > map

和临时QMAP QMap <QString, QVariant> tmpMap

我需要用内部QMAP的键和值填充临时QMAP,以便我可以

循环并输出嵌套QMAP的所有值。

这是我的代码

QMap <QString, QMap<QString, QVariant> > map;
QMap <QString, QVariant> tmpMap;
QList<QString> mapKeys = map.keys();
for(int index = 0; index < mapKeys.size(); ++index)
{
  tmpMap.unite(map.value(QString(index)));
  QList<QString> tmpMapKeys = tmpMap.keys()
    for(int index2 = 0, index2 < tmpMapKeys.size(); ++index2)
    {
      //Stuff to check and output
    }
}

但是,第二个循环永远不会运行,因为TMPMAP从未存储任何东西。

QString(index)不做您认为做的事情。您可能会想到QString::number(index),但即使那样,如果任何键的值都不是在有限的范围内您迭代的,则它也行不通。您确实应该使用mapKeys.at(index):它可以使您的代码工作。但是,您不应该将地图的钥匙复制到mapKeys中:这是过早的悲观。

值得庆幸的是,C 11'使所有这些简单简洁。您可以使用范围来迭代map的值 - 内图。然后,您可以使用推论型const-Iteritor来迭代累积的allInners地图的密钥/值对。

#include <QtCore>
int main() {
   QMap<QString, QMap<QString, QVariant>> map;
   QMap<QString, QVariant> allInners;
   // accumulate the inner keys/values
   for (auto const & inner : map)
      allInners.unite(inner);
   // process the inner keys/values
   for (auto it = allInners.cbegin(); it != allInners.cend(); ++it)
      qDebug() << it.key() << it.value();
}

就像柏拉图郡所说的那样,第一个循环中的钥匙尚不清楚,而不是:

tmpMap.unite(map.value(QString(index)));

尝试

tmpMap.unite(map.value(mapKeys.at(index)));

写作Map.Value(QString(index))是什么意思?至少对我来说这很模棱两可。例如,如果我编写QString(0x40),我将在其中获得一个带有 @ carture的字符串(0x40是其代码),并且您正在这样做,我想,即调用QString(int)。因此,请尝试更明确地写。

要通过一些容器进行迭代,我建议您使用非常有用的迭代器。用法正在遵循(不过测试代码):

QMap <QString, QMap<QString, QVariant> > map;
QMap <QString, QMap<QString, QVariant> >::const_iterator i;
QMap<QString, QVariant>::const_iterator i2;
for (i = map.begin(); i != map.end(); i++)
{
    for (i2 = i.value.begin(); i2 != i.value.end(); i2++)
    {
        //Access to all the keys and values of nested QMap here
        //i2.key() is some QString and i2.value() is some QVariant
        //Stuff to check and output
    }
}

afaik在QMAP,QHASH等诸如QMAP,QHASH等方面都没有通常的索引。如果您有一些QMAP,则需要知道确切的字符串才能根据某些QString获得"某物"。如果" Hello,World"转到Something smth,那么如果您编写Map.Value(" Hello,World"),您将获得此'SMTH'对象。要检查所有QMAP条目使用我上面提到的迭代器。

如果您需要通过其号码获得一些东西,那么我建议您使用Standart数组,列表,集合,队列,堆栈等

P.S。KMX78的方式也应该为您工作。