From ac67648317bc3f4de0a0d84a32b828c68f4abefd Mon Sep 17 00:00:00 2001 From: Max Lyon Date: Mon, 24 Aug 2020 14:54:45 +0200 Subject: [PATCH] add weighted average to smart ranges --- src/OpenMesh/Core/Mesh/SmartRange.hh | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/OpenMesh/Core/Mesh/SmartRange.hh b/src/OpenMesh/Core/Mesh/SmartRange.hh index 0277bd59..c3fba9f0 100644 --- a/src/OpenMesh/Core/Mesh/SmartRange.hh +++ b/src/OpenMesh/Core/Mesh/SmartRange.hh @@ -124,6 +124,34 @@ struct SmartRangeT return (1.0 / n_elements) * result; } + /** @brief Computes the weighted average of elements. + * + * Computes the weighted average of all elements in the range after applying the functor \p f. + * + * @param f Functor that is applied to all elements before computing the average. + * @param w Functor returning element weight. + */ + template + auto avg(Functor&& f, WeightFunctor&& w) -> typename std::decay())+w(std::declval())))*f(std::declval()))>::type + { + auto range = static_cast(this); + auto begin = range->begin(); + auto end = range->end(); + assert(begin != end); + typename std::decay::type weight = w(*begin); + typename std::decay::type result = weight * f(*begin); + typename std::decay::type weight_sum = weight; + auto it = begin; + ++it; + for (; it != end; ++it) + { + weight = w(*it); + result += weight*f(*it); + weight_sum += weight; + } + return (1.0 / weight_sum) * result; + } + /** @brief Check if any element fulfils condition. * * Checks if functor \p f returns true for any of the elements in the range.