我正在尝试Qt中的一些东西,并试图理解容器,但我碰到了一道砖墙。
QHash<int, QString> mHash;
mHash.insert(3, "Nocas");
mHash.insert(1, "Andre");
mHash.insert(2, "Diana"); //overrides
mHash.insertMulti(5, "Batatas"); //overides all keys '5'
qDebug() << "\nHash.keys()\n";
foreach(int i, mHash.keys())
{
qDebug() << i << " -> " << mHash[i];
}
qDebug() << "\nHash Values\n";
foreach(QString value, mHash)
{
qDebug() << "Value: " << value;
}
qDebug() << "\nPre Copy\n";
QHashIterator<int, QString> Hit(mHash);
while (Hit.hasNext())
{
Hit.next();
qDebug() << Hit.key() << " = " << Hit.value();
}
QMap<int, QString> HMap;
QMutableMapIterator<int, QString> it2h(HMap);
//Copy Hash to Map
while (Hit.hasNext())
{
Hit.next();
HMap.insert(Hit.key(), Hit.value());
}
qDebug() << "Print map: \n";
while (it2h.hasNext())
{
it2h.next();
qDebug() << it2h.key() << " = " << it2h.value();
}我不明白为什么:
while (Hit.hasNext())
{
Hit.next();
HMap.insert(Hit.key(), Hit.value());
}不起作用。
我看过文学作品,但我不太明白。我试过改变迭代器。
QMap<int, int>::const_iterator i;使用foreach,for...still nothing从不输出。
产出如下:
Hash.keys()
5 -> "Batatas"
1 -> "Andre"
3 -> "Nocas"
2 -> "Diana"
Hash Values
Value: "Batatas"
Value: "Andre"
Value: "Nocas"
Value: "Diana"
Pre Copy
5 = "Batatas"
1 = "Andre"
3 = "Nocas"
2 = "Diana"
Print map:正如您在“打印地图”之后所看到的那样:我期待这些值。
发布于 2019-12-31 18:24:15
QHashIterator<int, QString> Hit(mHash);
while (Hit.hasNext())
{
Hit.next();
qDebug() << Hit.key() << " = " << Hit.value();
}这些代码为散列映射创建一个迭代器,并对其进行迭代,这样hasNext函数就是false。正如输出所证明的那样,这是正确的。
QMap<int, QString> HMap;
QMutableMapIterator<int, QString> it2h(HMap);
//Copy Hash to Map
while (Hit.hasNext())
{
Hit.next();
HMap.insert(Hit.key(), Hit.value());
}接下来,代码试图再次迭代Hit --,但是它已经在的末尾了,并且不执行任何循环。应该通过使用调试器或向for循环添加print语句来验证这一点。
由于上面的循环没有执行,所以没有复制任何内容,因此QMap没有任何值。需要重置Hit迭代器,或者创建一个新的迭代器,以便在尝试迭代进行复制之前指向哈希映射的开始。
看起来有一个toFront API可以将迭代器重置回最前面,这样迭代就可以重新开始,参见https://doc.qt.io/qt-5/qhashiterator.html#toFront。我无法访问QT来测试和验证这种行为,因为我不这么做。
发布于 2019-12-31 19:23:28
我通过使用hasPrevious()来解决这个问题,因为他说指针将指向末尾。
QMap<int, QString> HMap; //I created the map
while (Hit.hasPrevious()) //used hasPrevious() to work my way back to the start
{
Hit.previous(); //pointed to previous on every loop
HMap.insert(Hit.key(), Hit.value()); //inserted on map
}
QMutableMapIterator<int, QString> itM(HMap);
qDebug() << "\nPost Copy\n";
while (itM.hasNext())
{
itM.next();
qDebug() << itM.key() << " = " << itM.value();
}因为我的目标是用地图来组织钥匙,所以它就像一种魅力。
这是我使用的最后一个解决方案:
Hit.toFront();
while (Hit.hasNext())
{
Hit.next();
HMap.insert(Hit.key(), Hit.value());
}https://stackoverflow.com/questions/59546618
复制相似问题