Commit fb3e8e4b authored by Davis King's avatar Davis King

Added max_scoring_element() and min_scoring_element()

parent b1589d2b
......@@ -1067,6 +1067,88 @@ namespace dlib
void* const data;
};
// ----------------------------------------------------------------------------------------
template <
typename T,
typename F
>
auto max_scoring_element(
const T& container,
F score_func
) -> decltype(std::make_pair(*container.begin(), 0.0))
/*!
requires
- container has .begin() and .end(), allowing it to be enumerated.
- score_func() is a function that takes an element of the container and returns a double.
ensures
- This function finds the element of container that has the largest score,
according to score_func(), and returns a std::pair containing that maximal
element along with the score.
- If the container is empty then make_pair(a default initialized object, -infinity) is returned.
!*/
{
double best_score = -std::numeric_limits<double>::infinity();
auto best_i = container.begin();
for (auto i = container.begin(); i != container.end(); ++i)
{
auto score = score_func(*i);
if (score > best_score)
{
best_score = score;
best_i = i;
}
}
using item_type = typename std::remove_reference<decltype(*best_i)>::type;
if (best_i == container.end())
return std::make_pair(item_type(), best_score);
else
return std::make_pair(*best_i, best_score);
}
// ----------------------------------------------------------------------------------------
template <
typename T,
typename F
>
auto min_scoring_element(
const T& container,
F score_func
) -> decltype(std::make_pair(*container.begin(), 0.0))
/*!
requires
- container has .begin() and .end(), allowing it to be enumerated.
- score_func() is a function that takes an element of the container and returns a double.
ensures
- This function finds the element of container that has the smallest score,
according to score_func(), and returns a std::pair containing that minimal
element along with the score.
- If the container is empty then make_pair(a default initialized object, infinity) is returned.
!*/
{
double best_score = std::numeric_limits<double>::infinity();
auto best_i = container.begin();
for (auto i = container.begin(); i != container.end(); ++i)
{
auto score = score_func(*i);
if (score < best_score)
{
best_score = score;
best_i = i;
}
}
using item_type = typename std::remove_reference<decltype(*best_i)>::type;
if (best_i == container.end())
return std::make_pair(item_type(), best_score);
else
return std::make_pair(*best_i, best_score);
}
// ----------------------------------------------------------------------------------------
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment