Finding position of a value in an array
Daren Scot Wilson
darenw at darenscotwilson.com
Tue Dec 31 04:38:53 UTC 2019
On Monday, 30 December 2019 at 23:15:48 UTC, JN wrote:
> On Sunday, 29 December 2019 at 08:31:13 UTC, mipri wrote:
>>
>> int i = a.countUntil!(v => v == 55);
>> assert(i == 2);
>
> I also had to ask because I couldn't find it. In other
> languages it's named "index()", "indexOf()" or "find()". D is
> the only language I know which uses the "countUntil" scheme.
> And even so it's not obvious from the name if it's the index of
> the element or number of preceding elements.
I had first tried myarray.index(myvalue) because I coulda sworn I
wrote exactly that syntax a only a few days ago. But I've been
hopping between languages, some D, some Crystal, some C++, some
Javascript, and with only two cerebral hemispheres, maybe I got
confused. So, D doesn't have index()? Is it called find()?
Something else? It was hard to find the right stuff in the
documentation.
So now I know about countUntil, and I'm glad the question has
gotten some traction for others to make progress with their code.
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"
More information about the Digitalmars-d-learn
mailing list