Linked List iterating over and inserting an element around (before/after) the current position.

Paul Backus snarwin at gmail.com
Sun May 19 23:15:26 UTC 2019


On Sunday, 19 May 2019 at 22:20:48 UTC, Josh wrote:
> Thank you, that helps big time.
>
> This is just more curiosity, but do you happen to know why I 
> have to use DList.linearRemove() instead of DList.remove()?
>
> import std.stdio;
> import std.container.dlist;
> import std.algorithm;
> import std.range;
>
> void main()
> {
>     auto list = make!DList("the", "quick", "brown", "fox");
>     auto range = list[].find("quick").take(1);
>     list.remove(range);
>     list[].each!writeln; // the brown fox
> }
>
> This results in a compiler issue:
>
> onlineapp.d(10): Error: function 
> std.container.dlist.Container!string.DList.remove(Range r) is 
> not callable using argument types (Take!(Range))
> onlineapp.d(10):        cannot pass argument range of type 
> Take!(Range) to parameter Range r
>
> Changing "remove" to "linearRemove" fixes it, but both the 
> remove and linearRemove functions take a Range object, and 
> linearRemove seems to just be a pass through to remove.

The documentation for DList.remove says that the range parameter 
"must be originally obtained from this container." A range 
returned from `take` doesn't qualify, since `take` returns a new 
range that wraps the original one. (`find` seems to be the 
exception rather than the rule, here, in that it actually returns 
the same type of range that's given to it.) However, the 2nd 
overload of linearRemove [1] is specifically written to accept a 
Take!Range, so it will work.

Fortunately, it is possible to accomplish what you want using 
DList.popFirstOf: [2]

     auto range = list[].find("quick");
     list.popFirstOf(range);

Full example: https://run.dlang.io/is/DCYtbp

[1] 
https://dlang.org/phobos/std_container_dlist.html#.DList.linearRemove.2
[2] 
https://dlang.org/phobos/std_container_dlist.html#.DList.popFirstOf


More information about the Digitalmars-d-learn mailing list