Created
December 19, 2015 15:44
-
-
Save goldsborough/8e85389223f0e79f19c6 to your computer and use it in GitHub Desktop.
C++ Template functions to find the best (e.g. max/min) of something.
This file contains hidden or 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
template<typename Iterator, typename Value> | |
struct Position | |
{ | |
Position(const Iterator& iterator_, const Value& value_) | |
: iterator(iterator_) | |
, value(value_) | |
{ } | |
Iterator iterator; | |
Value value; | |
}; | |
template<typename Iterator, typename Projection, typename Compare> | |
auto best(Iterator begin, | |
Iterator end, | |
Projection projection, | |
Compare compare) | |
{ | |
using Output = decltype(projection(*begin)); | |
auto best_iterator = begin; | |
auto best_value = projection(*begin); | |
for (++begin; begin != end; ++begin) | |
{ | |
auto&& value = projection(*begin); | |
if (compare(std::forward<Output>(value), best_value)) | |
{ | |
best_value = std::forward<Output>(value); | |
best_iterator = begin; | |
} | |
} | |
return Position<Iterator, Output>{best_iterator, best_value}; | |
} | |
template<typename Iterator, typename Projection> | |
auto maximum(Iterator begin, Iterator end, Projection projection) | |
{ | |
using Output = decltype(projection(*begin)); | |
return best(begin, end, projection, std::greater<Output>()); | |
} | |
template<typename Iterator, typename Projection> | |
auto minimum(Iterator begin, Iterator end, Projection projection) | |
{ | |
using Output = decltype(projection(*begin)); | |
return best(begin, end, projection, std::less<Output>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment