foreach automoatic counter?
Justin Whear via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 21 08:54:06 PDT 2015
On Mon, 21 Sep 2015 15:38:38 +0000, French Football wrote:
> Going through a book on coding in D,
> http://ddili.org/ders/d.en/foreach.html , I find the following very
> useful feature:
>
> When two names are specified in the names section [with a plain array],
> they represent an automatic counter and the value of the element,
> respectively:
> foreach (i, element; array) {
> writeln(i, ": ", element);
> }
>
> I understand that foreach is built on top of a for loop... I'm just
> wondering why I can't access the automatic counter from a doubly linked
> list, or an associative array, or some range? It's pretty common for me
> to have to rewrite foreach loops to be for loops when I get to the
> bottom and realize I need to know where in the sequence I am...
With an associative array the foreach becomes:
foreach (key, value; aa)
For arbitrary ranges you can use std.range.enumerate like this:
foreach (i, element; someRange.enumerate)
More information about the Digitalmars-d-learn
mailing list