Deleting some elements of a (forward) list while iterating

I have a list of objects, each of them has a different steps lifespan.
A cycle decreases the lifespan of each by 1, and when something reaches 0 i have to remove it from the list. I have pretty clear what i want to happen low-level-wise:

n = first node;
visit n, update lifespan. It is >0 =>
last = n =>

n = n.next
visit n, update lifespan. It is >0 =>
last = n =>

n = n.next
visit n, update lifespan. It is ==0 =>
last.next = n.next
delete n

n = last.next
...and go on.

Is there any way to do that with some fancy syntax before i end up rewriting custom::list? xD
I want to avoid looping them all twice or more per step.

Thanks for your time!

____________________________________
Edit: i wrote that thing with the added "last" pointer for a reason. You could do without it with a regular bidirectional list, but since my list is relatively big and i need it to use the least possible amount of memory, i would be using a forward list
Last edited on
It sounds like your list should be circular.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class CircularList{
    Node *head;
public:
    bool empty() const;
    Node &get_head();
    void rotate();
    void remove_head();
}

//...

while (!list.empty()){
    if (list.get_head().lifespan){
        list.rotate();
        continue;
    }
    list.remove_head();
}
1
2
3
4
5
6
7
8
9
10
11
// a cycle makes one pass through the forward list, decreasing the lifespan 
// of each object by 1, and removing the object if its lifespan reaches 0
void cycle( std::forward_list<object>& flist )
{
    auto prev = flist.before_begin() ;
    for( auto curr = flist.begin() ; curr != flist.end() ; )
    {
        if( --curr->lifespan == 0 ) curr = flist.erase_after(prev) ;
        else prev = curr++ ;
    }
}

http://coliru.stacked-crooked.com/a/07f9eeba5cd36b38
Topic archived. No new replies allowed.