View source code
Display the source code in std/algorithm/searching.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.algorithm.searching.maxIndex

Computes the index of the first occurrence of range's maximum element.

ptrdiff_t maxIndex(alias pred, Range) (
  Range range
)
if (isInputRange!Range && !isInfinite!Range && is(typeof(binaryFun!pred(range.front, range.front))));

Complexity

Ο(range) Exactly range.length - 1 comparisons are needed.

Parameters

NameDescription
pred The ordering predicate to use to determine the maximum element.
range The input range to search.

Returns

The index of the first encounter of the maximum in range. If the range is empty, -1 is returned.

Limitations

If at least one of the arguments is NaN, the result is an unspecified value. See maxElement for examples on how to cope with NaNs.

See Also

minIndex, max, maxCount, maxElement, maxPos

Example

// Maximum is 4 and first occurs in position 2
int[] a = [2, 3, 4, 1, 2, 4, 1, 1, 2];
writeln(a.maxIndex); // 2

// Empty range
int[] b;
writeln(b.maxIndex); // -1

// Works with more custom types
struct Dog { int age; }
Dog[] dogs = [Dog(10), Dog(15), Dog(5)];
writeln(dogs.maxIndex!"a.age < b.age"); // 1

Authors

Andrei Alexandrescu

License

Boost License 1.0.