CorArray: FindIndex

FindIndex

Searches for an element that matches the conditions defined by the specified callback method, and returns the lower-bound based index of the first occurrence within the range of elements in the array that starts at the specified index and contains the specified number of elements.



 Public Function FindIndex(
	  ByRef Arr As Variant,
	  ByVal AddressOfPredicate As Long,
	  Optional ByRef Index As Variant,
	  Optional ByRef Count As Variant ) As Long

Parameters

Arr
[ByRef] Variant. The one-dimensional array to be searched.
AddressOfPredicate
[ByVal] Long. The address of the callback function used to match the array elements.
Index
[ByRef] Optional. Variant. The starting index of the search.
Count
[ByRef] Optional. Variant. The number of elements in the section to search.

Return Values

Long -  The index of the first occurrence of an element that matches the conditions defined in the callback method, if found; otherwise the lower-bound of the array minus one.

Remarks

The AddressOfPredicate is an address to a method that returns True if the value passed to it matches the conditions defined in the callback method. The elements of Arr are individually passed to the callback method, and processing is stopped when a match is found.

The callback method should have a signature resembling the following:

 Public Function CallbackMethod(ByRef Value As <Type>) As Boolean
   ' Evaluate value
 End Function
 

It has one parameter that is defined as ByRef and should be the same type as the elements in the array to be searched.

It is extremely important to define the callback method correctly. If the method is incorrect, the application may crash.

The search is based on the array lower-bound, not zero-based.

Exceptions

ExceptionCondition
ArgumentNullExceptionArr is uninitialized.
ArgumentOutOfRangeException StartIndex is outside the range of valid indexes for Arr.
-or-
Count is less than zero.
-or-
StartIndex and Count do not specify a valid section in Arr.

Examples

The following example will search a given array for the first age that is over 25 and return the index.

Private Sub Main()
    Dim Ages() As Long
    Dim Index As Long
    
    Ages = NewLongs(14, 22, 31, 27, 18)
    
    ' To find the index of the first age over 25, pass the array and
    ' address of the callback method to CorArray.FindIndex.
    Index = CorArray.FindIndex(Ages, AddressOf AgeOver25)
    
    ' Dispay the index found.
    Debug.Print "The first age over 25 found at index " & Index
End Sub

' The method accepts a ByRef parameter of the array element type.
Private Function AgeOver25(ByRef Age As Long) As Boolean
    AgeOver25 = Age > 25
End Function

' This code example produces the following output.
'  The first age over 25 found as index 2

See Also

Project CorLib Overview

Class CorArray Overview

Exists

Find

FindLast

FindLastIndex

FindAll