Finding position of a value in an array

Paul Backus snarwin at gmail.com
Tue Dec 31 06:01:36 UTC 2019


On Tuesday, 31 December 2019 at 04:38:53 UTC, Daren Scot Wilson 
wrote:
>  I'm needing to see more examples.  It might have something to 
> do with the array I'm working with being inside a foreach loop. 
> My code looks like this, with the problematic line duplicated 
> to show some of the variations I tried:
>
>     import std.algorithm;
>
>     alias doo = ubyte;
>     struct Info
>     {
>         int x;
>         doo[NDOOS] doos;   // NDOOS = 10
>     }
>
>     immutable int INFO = 100000;
>     Info[NINFOS]  infos;    // global array, used heavily.
>
>     float foo_function(doo important_d)    {
>       ...
>       foreach (info; infos)    {
>
>         int i = info.doos.index(important_d);                  
> // #1
>         int i = info.doos.countUntil(d => d == important_d);   
> // #2
>         int i = info.doos.countUntil!(d => d == important_d);  
> // #3
>         int i = countUntil(d => d == important_d, info.doos);  
> // #4
>         int i = countUntil!(d => d == important_d)(info.doos); 
> // #5
>
>         if (i>=0)  {  // assuming -1 represents value not found
>              ... do stuff with i ...
>         }
>       }
>       ...
>     }
>
> All the lines shown give me
>
>     "template ... cannot deduce function from argument types..."
>
> but one time I got, but cannot reproduce now, the error
>     "Error: template instance countUntil!((d) => d == 
> important_d, doos) has no value"

countUntil operates on ranges, and static arrays aren't ranges. 
To get a range from a static array, you have to slice it with the 
`[]` operator:

     int i = info.doos[].countUntil(important_d);

(Why can't static arrays be ranges? Because ranges can shrink, 
via popFront, but a static array can never change its length.)


More information about the Digitalmars-d-learn mailing list