Traverse a DList and insert / remove in place?

Bastiaan Veelo Bastiaan at Veelo.net
Sat Mar 25 12:55:59 UTC 2023


On Sunday, 19 March 2023 at 13:15:58 UTC, Armando wrote:
> I would like to do something like traversing a DList, operating 
> on the current element, and potentially removing that element 
> or inserting a new one before/after it - an easy operation if 
> you code a DList yourself. Maybe I missed something?

This is one way to do that:
```d
import std;

struct MyType
{
     int id;
     // [...] other stuff
}

void main()
{
     auto list = DList!MyType();

     // Fill the list.
     foreach (i; 0 .. 10)
         list.insertBack(MyType(i));

     // Traverse the list, conditionally remove one element.
     for (auto range = list[]; !range.empty;)
         if (range.front.id == 3)
             list.popFirstOf(range);
         else
             range.popFront();

     // Traverse the list, conditionally insert one element.
     for (auto range = list[]; !range.empty;)
     {
         if (range.front.id == 6)
             list.insertBefore(range, MyType(66));
         range.popFront();
     }

     // Print modified list.
     foreach (e; list)
         writeln(e);

}
```

Output:
```
MyType(0)
MyType(1)
MyType(2)
MyType(4)
MyType(5)
MyType(66)
MyType(6)
MyType(7)
MyType(8)
MyType(9)
```

https://run.dlang.io/is/kk80FD

-- Bastiaan.


More information about the Digitalmars-d-learn mailing list