c++ - 使用 std::accumulate 以最佳精度添加 float

标签 c++ stl

我想将总数累加为 double 而不是 float 。

vector<float> v;
....
double total  = std::accumulate(v.begin(),
                                v.end(),
                                static_cast<double>(0.0));
//This compiles but I am not sure it is doing what I want

...

double total_ = std::accumulate<double>(v.begin(),
                                        v.end(),
                                        static_cast<double>(0.0)
                                       );

// This doesnt compile, which leads me to believe the first accumulate
// is coercing the double(0.0) back to float.

有没有STL惯用简洁的写法

double total = 0.0;
for (int i = 0; i < v.size(); ++i) {
  total += v[i];
}

只使用标准库。

我知道这不足以保持精度。

最佳答案

std::accumulate中使用的累加类型从第三个参数的类型推导出来。字面量 0.0 是一个 double,因此这使用 double 执行累加,无需显式转换:

double total  = std::accumulate(v.begin(), v.end(), 0.0);

相当于

double sum = 0.0;
for (f : v) sum += f;

关于c++ - 使用 std::accumulate 以最佳精度添加 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448747/

相关文章:

c++ - std::set 需要多少额外内存(如果有的话)来存储它的元素 v.s.一个 std::vector?

c++ - 如果我在下面的代码中使用列表而不是 vector ,为什么在我尝试在迭代器之间执行减法的那一行编译失败?

c++ - 识别 WinRT 的宏?

android - QT Necessitas - 链接 gnu-libstdc++ 时出现神秘的 ctype_base.h 错误

多重继承中的c++ vtable,指向thunk方法的指针

c++ - 重命名具有相同名称但不同扩展名的文件

C++:STL 链表 - 表示多项式

VS2008 中的 C++ STL:std::ostringstream 在大量分配/清除使用后抛出 std::bad_alloc

c++ - 如何将一个模块拆分成多个文件

c++ - 从 5x10^8 个不同的数组元素中读取,每次 4 个字节