指定调用std::copy的十进制精度

Specifying the decimal precision for a call to std::copy

本文关键字:十进制 精度 copy 调用 std      更新时间:2023-10-16

我有以下函数将矢量保存为CSV文件:

#include <math.h>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
bool save_vector(vector<double>* pdata, size_t length,
                 const string& file_path)
{
  ofstream os(file_path.c_str(), ios::binary | ios::out);
  if (!os.is_open())
    {
      cout << "Failure!" << endl;
      return false;
    }
  copy(pdata->begin(), pdata->end(), ostream_iterator<double>(os, ","));
  os.close();
  return true;
}

在生成的CSV文件中,pdata中的数字以可变精度保存,并且没有一个以我想要的精度保存(小数点后10位)。

我知道函数std::setprecision。但是,这个函数,根据文档

只能用作流操纵符。

(我实际上不确定我是否正确地解释了"流操纵器";我假设这意味着我不能在当前编写的函数中使用它。)

是否有一种方法可以让我指定使用copy函数的十进制精度?如果不是,我应该如何摆脱copy,以便我可以在上面的函数中使用setprecision ?

可以调用

os.precision(10);