从嵌套的 QMap 中获取价值

Getting Value out of Nested QMap

我有一个嵌套的 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
    }
}

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

写map.value(QString(index))是什么意思? 至少对我来说,这是非常模棱两可的。例如,如果我写 QString(0x40),我将得到一个带有 @ 字符的字符串(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,那么您需要知道确切的字符串才能根据某些 QString 获得 'Something'。如果 "Hello, world" 转到 Something smth 那么如果你写 map.value("Hello, world") 你会得到这个 'smth' 对象。要检查所有 QMap 条目,请使用我上面提到的迭代器。

如果您需要按编号获取某些东西,那么我建议您使用标准数组、列表、集合、队列、堆栈等。

P.S。 kmx78的方法应该也适合你。

如platonshubin所说,第一个循环中的关键不太清楚,而不是:

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

尝试

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

QString(index) 并不像您想象的那样。您可能会想到 QString::number(index),但即便如此,如果任何键的值不是您迭代的有限范围内的数字,它也不会起作用。您真的应该使用 mapKeys.at(index):它会让您的代码正常工作。但是您根本不应该将地图的键复制到 mapKeys 中:这是过早的悲观情绪。

值得庆幸的是,C++11' 使所有这些变得简单而简洁。您可以使用 range-for 来迭代 map 的值 - 内部映射。然后您可以使用推导类型的常量迭代器来迭代累积的 allInners 映射的 key/value 对。

#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();
}