C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] arg_min and arg_max algorithms
From: Arthur O'Dwyer (arthur.j.odwyer_at_[hidden])
Date: 2020-12-15 20:23:59


On Tue, Dec 15, 2020 at 8:00 PM Jason Beach via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi,
> I recently wrote a simple particle filter for a robotics project and
> needed an arg_min function. This function returns the argument that
> results in a minimum value of a function (as opposed to the minimum
> argument value itself https://en.wikipedia.org/wiki/Arg_max). In my case,
> from a list of points I needed to find the point that was closest to
> another given point.
>
> I based my implementation on the examples given on cppreference for
> std::transform and std::min_element. The major advantage of a combined
> algorithm as opposed to using std::transform and std::min_element
> individually is that it cuts the number of function evaluations in half by
> caching the result.
>

This smells a lot like std::ranges::min_element with a projection:
https://godbolt.org/z/9fE7r8

auto arg_min(auto first, auto last, auto unary_op) {
    auto it = std::ranges::min_element(first, last, std::less(), unary_op);
    return std::make_pair(it, it == last ? std::nullopt :
std::make_optional(unary_op(*it)));
}

I admit that my version does one more evaluation of unary_op(*it) than
yours does; but maybe that's acceptable?

-Arthur



STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups