Skip to content

Instantly share code, notes, and snippets.

@jasonbeach
Created April 25, 2020 05:15
Show Gist options
  • Save jasonbeach/215c23ea6b3b4b4b246f4455d32daba0 to your computer and use it in GitHub Desktop.
Save jasonbeach/215c23ea6b3b4b4b246f4455d32daba0 to your computer and use it in GitHub Desktop.
Find minimum element while transforming the elements
// This is meant to minimic std::minimum_element, but allows you to transform the
// element in some way. We could use std::minimum_element, but the transform function
// would be evaluated twice as many times as it needs to be as it's results aren't
// cached. This caches the value.
template<class ForwardIt, class UnaryOperation>
ForwardIt min_transformed_element(ForwardIt first, ForwardIt last, UnaryOperation unary_op)
{
if (first == last) return last;
ForwardIt smallest = first;
auto smallest_val = unary_op(*first);
++first;
for (; first != last; ++first) {
auto first_val = unary_op(*first);
if (first_val < smallest_val) {
smallest = first;
smallest_val = first_val;
}
}
return smallest;
}
// https://wandbox.org/permlink/Mvr69yFIMtxQB7yy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment