简体   繁体   English

使用模板计算向量的平均值

[英]Calculating average of vectors using templates

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::arrays s. 我做了一个简单的函数,它接受2 std::array并返回另一个std::array ,其中包含std::arrays s中值的平均值。

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. 现在我想计算N个向量的平均值。 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? 我想不出另一种方式,有人可以帮助我吗?

Provided that you'd also made the necessary changes in the body of the template function. 前提是您还在模板功能的主体中进行了必要的更改。 You could change the signature of your template function as follows: 您可以更改模板函数的签名,如下所示:

template<typename T, std::size_t N, typename... Ts>
std::array<T, N> average(std::array<T, N> const &arr, const Ts&... args)

This way you wouldn't have to specify the template arguments explicitly and template argument deduction would deduce T and N and thus you could call your average template function as: 这样您就不必明确指定模板参数,模板参数推导会推导出TN ,因此您可以将average模板函数称为:

std::array<int, 3> a{ 1, 2, 3 };
std::array<int, 3> b{ 3, 4, 5 };

auto c = average(a, b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM