我有一个嵌套的 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 从不存储任何东西。
最佳答案
QString(index)
并不像您想象的那样。您可能会想到 QString::number(index)
,但即便如此,如果任何键的值不是您迭代的有限范围内的数字,它也不会起作用。您真的应该使用 mapKeys.at(index)
:它会让您的代码正常工作。但是您根本不应该将 map 的键复制到 mapKeys
中:这是过早的悲观情绪。
值得庆幸的是,C++11' 使所有这些变得简单而简洁。您可以使用 range-for 迭代值 - map
的内部映射。然后您可以使用推导类型的常量迭代器来迭代累积的 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();
}
关于c++ - 从嵌套的 QMap 中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999901/