Created
April 25, 2020 05:15
-
-
Save jasonbeach/215c23ea6b3b4b4b246f4455d32daba0 to your computer and use it in GitHub Desktop.
Find minimum element while transforming the elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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