ipa: libipa: vector: Add sum() function

Add a function to calculate the sum of a vector. It will be useful for
algorithms.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Reviewed-by: Milan Zamazal <mzamazal@redhat.com>
This commit is contained in:
Laurent Pinchart 2024-11-16 21:02:52 +02:00
parent 2a29a2a6a1
commit 5ad6b3b1bb
2 changed files with 19 additions and 0 deletions

View file

@ -289,6 +289,18 @@ namespace ipa {
* \return The length of the vector * \return The length of the vector
*/ */
/**
* \fn Vector::sum() const
* \brief Calculate the sum of all the vector elements
* \tparam R The type of the sum
*
* The type R of the sum defaults to the type T of the elements, but can be set
* explicitly to use a different type in case the type T would risk
* overflowing.
*
* \return The sum of all the vector elements
*/
/** /**
* \fn Vector<T, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<T, Cols> &v) * \fn Vector<T, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<T, Cols> &v)
* \brief Multiply a matrix by a vector * \brief Multiply a matrix by a vector

View file

@ -10,6 +10,7 @@
#include <array> #include <array>
#include <cmath> #include <cmath>
#include <functional> #include <functional>
#include <numeric>
#include <optional> #include <optional>
#include <ostream> #include <ostream>
@ -239,6 +240,12 @@ public:
return std::sqrt(length2()); return std::sqrt(length2());
} }
template<typename R = T>
constexpr R sum() const
{
return std::accumulate(data_.begin(), data_.end(), R{});
}
private: private:
template<class BinaryOp> template<class BinaryOp>
static constexpr Vector apply(const Vector &lhs, const Vector &rhs, BinaryOp op) static constexpr Vector apply(const Vector &lhs, const Vector &rhs, BinaryOp op)