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.minElement
Iterates the passed range and returns the minimal element.
A custom mapping function can be passed to map
.
In other languages this is sometimes called argmin
.
auto minElement(alias map, Range)
(
Range r
)
if (isInputRange!Range && !isInfinite!Range);
auto minElement(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
Name | Description |
---|---|
map | custom accessor for the comparison key |
r | range from which the minimal element will be selected |
seed | custom seed to use as initial element |
Precondition
If a seed is not given, r
must not be empty.
Returns
The minimal element of the passed-in range.
Note
If at least one of the arguments is NaN, the result is an unspecified value.
If you want to ignore NaNs, you can use filter
and std
to remove them, before applying minElement.
Add a suitable seed, to avoid error messages if all elements are NaNs:
<range> .filter!(a=>!a .isNaN) .minElement(<seed>);
If you want to get NaN as a result if a NaN is present in the range,
you can use fold
and std
:
<range> .fold!((a,b)=>a .isNaN || b .isNaN ? real .nan : a < b ? a : b);
See Also
Example
import std .range : enumerate;
import std .typecons : tuple;
writeln([2, 7, 1, 3] .minElement); // 1
// allows to get the index of an element too
writeln([5, 3, 7, 9] .enumerate .minElement!"a.value"); // tuple(1, 3)
// any custom accessor can be passed
writeln([[0, 4], [1, 2]] .minElement!"a[1]"); // [1, 2]
// can be seeded
int[] arr;
writeln(arr .minElement(1)); // 1
Authors
License
Copyright © 1999-2024 by the D Language Foundation | Page generated by ddox.