I made a simple function that takes 2 std::array and returns another std::array with the average values of the values in the std::arrayss.
template<typename T, std::size_t N>
std::array<T, N> average(const std::array<T, N>& a1, const std::array<T, N>& a2)
{
std::array<T, N> array;
for (std::size_t i = 0; i < N; ++i)
array[i] = (a1[i] + a2[i]) / 2;
return array;
}
Works perfectly. Now I would like to calculate the average of N vectors. So I made this
template<typename T, std::size_t N, typename... Ts>
std::array<T, N> average(const Ts&... args)
{
std::array<T, N> result;
for (std::size_t i = 0; i < N; ++i)
{
T addedValues = 0;
for (const auto& array : { args... })
addedValues += array[i];
result[i] = addedValues / sizeof...(args);
}
return result;
}
Which also works, but I have to specify the resulting template arguments
std::array<int, 3> a{ 1, 2, 3 };
std::array<int, 3> b{ 3, 4, 5 };
auto c = average<int, 3>(a, b); //'<int, 3>' not good, possible without?
I couldn't think of another way, can somebody help me please?
Aucun commentaire:
Enregistrer un commentaire