从嵌套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
}
}
但是,第二个循环永远不会运行,因为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的方式也应该为您工作。
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 嵌套的匿名命名空间
- 了解嵌套循环打印星号图案
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 嵌套for循环C++的问题(初学者)
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 用C#中的并集模拟C++嵌套结构
- 部分专业化和嵌套模板
- 嵌套While循环不起作用(C++问题)
- C++-模板嵌套类的引用初始化无效
- 如何在嵌套类中正确使用友元声明?
- 从嵌套QMAP中获得价值