Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
MSalters Avatar asked Jul 18 '13 09:07

MSalters


1 Answers

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

like image 113
TemplateRex Avatar answered Nov 11 '22 09:11

TemplateRex