Reputation: 1456
I am working on a non-binary tree structure, and so for that I have a struct defined as follows which has a data and all it's child are in a vector called child.
struct node{
string data;
vector< node* > child;
vector<node*>::iterator i
int Count;
};
I have another function that I have defined to print the child in the vectors, but I can't get the iterator working
void printTree(node* &a){
for(a->i = a->child.begin(); a->i !=a->child.end();++i)
cout << *(a->i)->data <<endl;
}
I am getting an error that the iterator isn't defined when printTree is called. I tried defining the iterator inside printTree function but I keep getting an error. Any suggestions on how should I change my code?
Upvotes: 0
Views: 1158
Reputation: 63481
Please take the iterator out of your node
structure.
void printTree(node* &a)
{
for( vector<node*>::iterator i = a->child.begin(); i != a->child.end(); i++ )
{
cout << (*i)->data << endl;
}
}
[edit]
Even I confused myself when I wrote this answer. Quite often I save myself from ugly and potentially confusing iterator dereferencing by doing this inside the loop:
node * n = *i;
cout << n->data << endl;
More generally, if I have SomeContainer<SomeType>
, I do this:
for( SomeContainer<SomeType>::iterator i = foo.begin(); i != foo.end(); i++ )
{
SomeType & val = *i;
// ...
}
The above approach is particularly handy when you are iterating through a map
and have to use i->second
to get your data instead of *i
.
Upvotes: 3