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
// 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++ ;
}
}