Thread overview
get element index when using each!(x)
Sep 17
JG
September 17
hi,

is there any way to get the index for an element when iteration using each!(x)?

 I know I can do this using foreach statement, but I prefer using the each template.

-----------
string s = "hello";
foreach(i, c; s) {
}
----------

how can I get to ?


Thanks!

binghoo dang
September 17
On Thursday, 17 September 2020 at 00:51:54 UTC, dangbinghoo wrote:
> hi,
>
> is there any way to get the index for an element when iteration using each!(x)?
>
>  I know I can do this using foreach statement, but I prefer using the each template.
>
> -----------
> string s = "hello";
> foreach(i, c; s) {
> }
> ----------
>
> how can I get to ?
>
>
> Thanks!
>
> binghoo dang

Perhaps there are other ways, but you can use enumerate. For example
-----------
import std.algorithm;
import std.range;
import std.stdio;
void main() {
 string s = "hello";
 s.enumerate.each!(x=>writeln(x[0],":",x[1]));
}
-----------
Produces
-----------
0:h
1:e
2:l
3:l
4:o
-----------
September 17
On Thursday, 17 September 2020 at 03:14:08 UTC, JG wrote:
>
> Perhaps there are other ways, but you can use enumerate. For example
> -----------
> import std.algorithm;
> import std.range;
> import std.stdio;
> void main() {
>  string s = "hello";
>  s.enumerate.each!(x=>writeln(x[0],":",x[1]));
> }

Worth knowing that the tuples you get from enumerate actually have named members, so you can write:

    s.enumerate.each!(x => writeln(x.index, ":", x.value));

Documentation: http://dpldocs.info/experimental-docs/std.range.enumerate.html
September 17
On Thursday, 17 September 2020 at 03:16:42 UTC, Paul Backus wrote:
> On Thursday, 17 September 2020 at 03:14:08 UTC, JG wrote:
>>
>> Perhaps there are other ways, but you can use enumerate. For example
>> -----------
>> import std.algorithm;
>> import std.range;
>> import std.stdio;
>> void main() {
>>  string s = "hello";
>>  s.enumerate.each!(x=>writeln(x[0],":",x[1]));
>> }
>
> Worth knowing that the tuples you get from enumerate actually have named members, so you can write:
>
>     s.enumerate.each!(x => writeln(x.index, ":", x.value));
>
> Documentation: http://dpldocs.info/experimental-docs/std.range.enumerate.html

thanks you! and thanks to JG.

---------
binghoo
September 18
On 2020-09-17 05:16, Paul Backus wrote:

> Worth knowing that the tuples you get from enumerate actually have named members, so you can write:
> 
>      s.enumerate.each!(x => writeln(x.index, ":", x.value));

It actually works out of the box for `each`:

s.each!((index, value) => writeln(index, ":", value));

https://dlang.org/phobos/std_algorithm_iteration.html#.each

-- 
/Jacob Carlborg