foreach automoatic counter?

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 21 12:23:37 PDT 2015


On Monday, 21 September 2015 at 16:32:25 UTC, French Football 
wrote:
> On Monday, 21 September 2015 at 15:54:06 UTC, Justin Whear 
> wrote:
>>
> On Monday, 21 September 2015 at 15:58:12 UTC, cym13 wrote:
>> 
>
> Thankyou! .enumerate lets me iterate over a container with a 
> counter.
>
> --Related tangential question... If I have a DList, how do I 
> insert into the middle of it? I'm trying .insertAfter but it 
> wants a range and apparently I can only slice an entire Dlist 
> with [].

I had to look into phobos sources 
(/usr/include/dlang/dmd/std/containers/dlist.d) to find a 
unittest, and judging from it it seems inserting in the middle of 
a DList just wasn't taken seriously.

     @safe unittest
     {
         import std.algorithm : equal;

         auto dl = DList!string(["a", "b", "d"]);
         dl.insertAfter(dl[], "e"); // insert at the end
         assert(equal(dl[], ["a", "b", "d", "e"]));
         auto dlr = dl[];
         dlr.popBack(); dlr.popBack();
         dl.insertAfter(dlr, "c"); // insert after "b"
         assert(equal(dl[], ["a", "b", "c", "d", "e"]));
     }

There is however a nicer method using std.ranges:

     void main(string[] args) {
         import std.stdio;
         import std.range;
         import std.container: DList;

         auto list = DList!int([1, 2, 3, 5]);

         list.insertBefore(list[].drop(3), 4);

         foreach(n ; list)
             writeln(n);
     }

I hope this is helpful.



More information about the Digitalmars-d-learn mailing list