View Full Version : [SOLVED]Use of Iterator to access a QList
graciano
22nd March 2010, 15:34
Hi,
Here is the code:
#include <QDebug>
#include <QList>
class Node
{
public:
int a;
int b;
};
int main(int argc, char *argv[])
{
//case1
QList<int> list1;
list1.append(10);
list1.append(3);
QList<int>::iterator i;
for (i = list1.begin(); i != list1.end(); ++i)
qDebug() << *i;
//case2
QList<Node> list2;
Node no = {10, 3};
list2.append(no);
QList<Node>::iterator j;
for (j = list2.begin(); j != list2.end(); ++j)
//here ???
;
}
In case 2, how can i access the a and b from each node?
Thanks
Lykurg
22nd March 2010, 16:00
*i.a;But I would preferre the index based approach for lists...
JohannesMunk
22nd March 2010, 16:02
Good work, asking with a minimal compilable program!
//case2
QList<Node> list2;
Node no = {11, 12};
list2.append(no);
QList<Node>::iterator j;
for (j = list2.begin(); j != list2.end(); ++j)
{
qDebug() << (*j).a << (*j).b;
}
HIH
Johannes
graciano
22nd March 2010, 16:03
humm ... are you certain of this?
graciano
22nd March 2010, 16:06
ahhh ... ok ...
qDebug() << (*j).a << (*j).b;
TANKS
Lykurg
22nd March 2010, 16:08
Damn, of course the brackets...:p
JohannesMunk
22nd March 2010, 16:12
Just wanted to apologize for the cross/double post.. but, yes, that's right. You need the brackets.
You should consider, using a constructor for your class, which initializes those properties. Or use a struct and plain old c. :->
#include <QApplication>
#include <QDebug>
#include <QList>
class Node
{
public:
int a;
int b;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
//case1
QList<int> list1;
list1.append(10);
list1.append(3);
QList<int>::iterator i;
for (i = list1.begin(); i != list1.end(); ++i)
qDebug() << *i;
//case2
QList<Node> list2;
Node no = {11, 12};
list2.append(no);
QList<Node>::iterator j;
for (j = list2.begin(); j != list2.end(); ++j)
{
qDebug() << (*j).a << (*j).b;
}
return 0;
}
Johannes
JohannesMunk
22nd March 2010, 16:13
Again :-> I should type faster!
norobro
22nd March 2010, 16:15
How about
qDebug() << j->a << j->b;
norobro
22nd March 2010, 16:17
Again :-> I should type faster!
I'm a little slow today also!
JohannesMunk
22nd March 2010, 16:25
Slow, but you contributed something new, anyhow :->
But as the iterator itself, is not a pointer type, that might seem strange..
It has its *-operator overloaded to return the item, and (*a). is equivalent to a-> .. compiler magic.
Well its a matter of taste, I guess.
Joh
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.