Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created December 19, 2015 15:44
Show Gist options
  • Save goldsborough/8e85389223f0e79f19c6 to your computer and use it in GitHub Desktop.
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.
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