@@ -302,6 +302,18 @@ namespace ipa {
* \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)
* \brief Multiply a matrix by a vector
@@ -10,6 +10,7 @@
#include <array>
#include <cmath>
#include <functional>
+#include <numeric>
#include <optional>
#include <ostream>
@@ -251,6 +252,12 @@ public:
return std::sqrt(length2());
}
+ template<typename R = T>
+ constexpr R sum() const
+ {
+ return std::accumulate(data_.begin(), data_.end(), R{});
+ }
+
private:
static constexpr Vector apply(const Vector &lhs, const Vector &rhs, std::function<T(T, T)> func)
{