Search code examples
c++algorithmc++11iteratorprojection

Is there a variant of min_element which takes a projection function?


std::min_element will return the smallest element as defined either by operator<(T,T) or by a custom predicate bool Pred(T,T). Is there a similar function which returns the element for which the projection function f(T)->R takes on the minimal value?

Obviously I can define bool Pred(t1,t2) { return f(t1) < f(t2); } but that's a bit inconvenient when f is a lambda.


Solution

  • Why not just define a predicate generator less_by which, taking a lambda, returns a functor that does the job for you?

    template <typename Proj>
    struct less_by_t {
        Proj p;
    
        template <typename T>
        bool operator ()(T const& a, T const& b) const {
            return p(a) < p(b);
        }
    };
    
    template <typename Proj>
    less_by_t<Proj> less_by(Proj p) {
        return {p};
    }
    
    auto result = std::min_element(begin, end, less_by([](T const& x){return …;}));