【问题标题】:How should we use template with std::accumulate in a function to return right type by cosidering template not "init"我们应该如何在函数中使用带有 std::accumulate 的模板来通过考虑模板而不是“init”来返回正确的类型
【发布时间】:2017-05-26 13:14:42
【问题描述】:

std::accumulate 的返回类型取决于“init”,即如果是整数则返回整数,如果是双精度则返回双精度。

我有一个这样的 sum 模板函数:

T mean(std::vector<T> vector)
{
    T sum = std::accumulate(vector.begin(), vector.end(), X);
}

我应该用什么代替X

【问题讨论】:

    标签: c++ c++11 templates


    【解决方案1】:

    您可以只使用T{},它是默认构造的T。例如

    T sum = std::accumulate(vector.begin(), vector.end(), T{});
    

    如果你需要用一些初始值来初始化它,你可以

    T sum = std::accumulate(vector.begin(), vector.end(), T{some_initial_value});
    

    T sum = std::accumulate(vector.begin(), vector.end(), static_cast<T>(some_initial_value));
    

    【讨论】:

    • 方法不对。它导致溢出。例如:如果您有无符号 __int16 的向量并且您想找到这些元素的总和,std::accumulate 会将结果存储在无符号 __int16 中(最大值 65535)。但是如果元素总和超过 65535 怎么办?
    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2023-02-22
    • 2020-06-21
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多