Finding position of a value in an array

mipri mipri at minimaltype.com
Mon Dec 30 19:58:17 UTC 2019


On Monday, 30 December 2019 at 19:46:50 UTC, Ron Tarrant wrote:
> 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
>
> ```

Compare:

   import std.stdio;
   import std.algorithm;
   import std.conv;

   void main(string[] args)
   {
   	MyObject[] objectArray;
   	MyObject newObject;
   	MyObject findPointer;
   	long index;

   	int foundObjectIndex;

   	for(int i; i < 12; i++)
   	{
   		newObject = new MyObject();
   		objectArray ~= newObject;

   		if(i is 5)
   		{
   			findPointer = newObject;
   		}
   	}

   	for(int i; i < objectArray.length; i++)
   	{
   		writeln("object: ", cast(MyObject*)objectArray[i]);
   	}

   	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]);

   } // main()


   class MyObject {}

With output:

   object: 7F2DC37C3000
   object: 7F2DC37C3020
   object: 7F2DC37C3030
   object: 7F2DC37C3040
   object: 7F2DC37C3050
   object: 7F2DC37C3060
   object: 7F2DC37C3070
   object: 7F2DC37C3080
   object: 7F2DC37C3090
   object: 7F2DC37C30A0
   object: 7F2DC37C30B0
   object: 7F2DC37C30C0
   findPointer: x297.MyObject, at address: 7F2DC37C3060 is a 
MyObject pointer in the objectArray with an index of 5, address: 
7F2DC37C3060



More information about the Digitalmars-d-learn mailing list