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.
Why not use a boost::transform_iterator (which used to be called projection_iterator_adaptor) from the Boost.Iterator library
auto Pred = [](some_value_type const& x){ /* your lambda here */ };
auto result = std::min_element(
boost::make_transform_iterator(begin(container), Pred),
boost::make_transform_iterator(end(container), Pred)
).base();
//^^^^^^^ <-- to get back an iterator to the original sequence
The advantage of this over writing a special less predicate are that you can reuse this approach for all other algorithms (e.g. for std::max_element you would need a special greater predicate etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With