tags:

views:

32

answers:

2

Hello everybody! Exscusme buy my English )))

I have this problem: I must iterate items in STL list with posible editing items: remove, add, edit. This is my approach:

void MoveOnNewPlace(Tree& parent, Tree& child)
{

    Tree *temp=&parent;
    while(temp->GetParent()!=temp && temp->GetItem().GetChar()=='(')
        temp=temp->GetParent();
    if(*temp==parent) return;
    Tree newTr(child);
    newTr.SetParent(*temp);
    temp->GetSubNodes()->push_back(newTr); //(Tree(child,temp));
    parent.GetSubNodes()->remove(child);

}

list<Tree>::_Nodeptr ptr=nodes->_Myhead->_Next;
    unsigned int i=0;
    while(i++<nodes->size() && ptr!=0)
    {
        Prepair(ptr->_Myval);
        if(ptr->_Myval.GetItem().GetChar()=='[')
            MoveOnNewPlace(t,ptr->_Myval);
        ptr=ptr->_Next;
    }

Could someone tell me how I can do it in other way without explicity using _Myhead, _Myhead and so on. Thanks!

+1  A: 

Have you considered using list<Tree>::iterator and list<Tree>::const_iterator?

for (list<Tree>::iterator i = list.begin(); i != list.end(); ++i) {
    ...do stuff with *i...
}
David Thornley
If I use list<Tree>::const_iterator then I get compilation error,if I use list<Tree>::iterator I get runtime error, because items of list can be deleted and it cause memory access violation.
Roman
Unfortunately, it doesn't work.
Roman
A: 

I see why you're trying to avoid using an iterator because you're modifying the list. You've correctly honed in on the problem that iterators are invalidated when you change the item they're iterating over. However, I'd still go with an iterator.

The insert function of a list will fix part of the problems for you. erase will also remove an item while returning an iterator to the next item on the list.

wheaties