Finding position of a value in an array
Ron Tarrant
rontarrant at gmail.com
Mon Dec 30 19:46:50 UTC 2019
On Monday, 30 December 2019 at 19:39:04 UTC, mipri wrote:
> You can definitely do it:
>
> $ rdmd --eval 'int a, b, c; [&a, &b,
> &c].countUntil(&c).writeln'
> 2
>
> But you need to have an array of pointers.
Thanks, mipri. Got it sorted. Here's a working proof...
```
import std.stdio;
import std.algorithm;
import std.conv;
void main(string[] args)
{
MyObject[] objectArray;
MyObject newObject;
MyObject findPointer;
long index;
int lastObjectID = 7;
int foundObjectIndex;
for(int i; i < 12; i++)
{
lastObjectID++;
newObject = new MyObject(lastObjectID);
objectArray ~= newObject;
if(i is 5)
{
findPointer = newObject;
}
}
for(int i; i < objectArray.length; i++)
{
writeln("object: ", cast(MyObject*)objectArray[i], ", ID: ",
objectArray[i].objectID);
}
index = objectArray.countUntil(findPointer);
writeln("findPointer: ", findPointer, ", at address: ",
cast(MyObject*)findPointer, " is a MyObject pointer in the
objectArray with an index of ", index, ", address: ",
cast(MyObject*)objectArray[index], ", ID: ",
objectArray[index].objectID);
} // main()
class MyObject
{
int objectID;
this(int ordinal)
{
objectID = ordinal;
} // this()
} // class MyObject
```
More information about the Digitalmars-d-learn
mailing list