PDA

View Full Version : Loop or Nested Iterator



enricong
27th September 2011, 23:22
I would like to use QHashIterator (or any of the iterators) in a loop. how to I re-assign the object the iterator is iterating over? I would need to do this for a nested iterator too.

Example:


QHash<QString, QHash<int,float> > testhash;

// code to populate hashes

QHashIterator<QString, QHash<int,float> > i(testhash);
while (i.hasNext())
{
i.next();
QHashIterator<int,float> j(i.value());
while (j.hasNext())
{
//get data
}
}


How do I reinitialize j in every loop? If I leave the code as is, j will have extra values.

ChrisW67
28th September 2011, 03:16
"j" is created every time through the outer while loop and ceases to exist before the next loop starts. There is no "reinitialize" they are separate instances in each outer loop. I have no idea what you mean by "j will have extra values". This:


#include <QtCore>
#include <QDebug>

QHash<QString, QHash<int,float> > testhash;

int main(int argc, char **argv) {
QCoreApplication app(argc, argv);

// code to populate hashes
for (int i = 0; i < 4; ++i ) {
QString key = QString("Key %1").arg(i);
testhash[key] = QHash<int,float>();
for (int j = 0; j < 3; ++j) {
testhash[key][j] = j * 3.0 ;
}
}

QHashIterator<QString, QHash<int,float> > i(testhash);
while (i.hasNext())
{
i.next();
qDebug() << "Outer key" << i.key();
QHashIterator<int,float> j(i.value());
while (j.hasNext())
{
j.next();
//get data
qDebug() << "Inner" << j.key() << j.value();
}
}

}
outputs nothing unexpected.


Outer key "Key 0"
Inner 0 0
Inner 1 3
Inner 2 6
Outer key "Key 1"
Inner 0 0
Inner 1 3
Inner 2 6
Outer key "Key 2"
Inner 0 0
Inner 1 3
Inner 2 6
Outer key "Key 3"
Inner 0 0
Inner 1 3
Inner 2 6

enricong
28th September 2011, 04:59
That is what I thought (that there is no need to reinitialize).

However, using the debugger, if I set a breakpoint inside the inner loop and look at "j" in each look and compare it to testhash, j will sometimes contain more elements.

for example, if I expect the following:


outer key 1:
0 10
1 11
2 12
3 13
4 14
outer key 2
0 100
1 111



I get something like


outer key 1:
0 10
1 11
2 12
3 13
4 14
outer key 2
0 100
1 111
2 12
3 13
4 14



It seems like I am getting extra keys and it seems to match with other elements in outer keys.
I'll have to try a simple example and see if the problem still exists and see where I'm screwing up.

ChrisW67
28th September 2011, 07:06
You will also get extra entries if you use hash[key] syntax for a key that does not exist, but those entries would be zero (default constructed) unless you set them.

The problem may lie in building the hash of hashes in the first place... perhaps you are not creating a new internal hash but using one that persists.