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.maxElement

Iterates the passed range and returns the maximal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmax.

auto maxElement(alias map, Range) (
  Range r
)
if (isInputRange!Range && !isInfinite!Range);

auto maxElement(alias map, Range, RangeElementType) (
  Range r,
  RangeElementType seed
)
if (isInputRange!Range && !isInfinite!Range && !is(CommonType!(ElementType!Range, RangeElementType) == void));

Complexity

O(n) Exactly n - 1 comparisons are needed.

Parameters

NameDescription
map custom accessor for the comparison key
r range from which the maximum element will be selected
seed custom seed to use as initial element

Returns

The maximal element of the passed-in range.

Note

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

See Also

minElement, max, maxCount, maxIndex, maxPos

Example

import std.range : enumerate;
import std.typecons : tuple;
writeln([2, 1, 4, 3].maxElement); // 4

// allows to get the index of an element too
writeln([2, 1, 4, 3].enumerate.maxElement!"a.value"); // tuple(2, 4)

// any custom accessor can be passed
writeln([[0, 4], [1, 2]].maxElement!"a[1]"); // [0, 4]

// can be seeded
int[] arr;
writeln(arr.minElement(1)); // 1

Authors

Andrei Alexandrescu

License

Boost License 1.0.