保存并从文件C ++中读取双重向量 [英] Save & read double vector from file C++

查看:147
本文介绍了保存并从文件C ++中读取双重向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 std :: vector< double> 保存到文件并读取以重建 std :: vector< double> ; 。来自rex的这段代码(原始答案)适用于 std :: vector< char> ,但不用于双打。一旦我尝试将其修改为可以使用双精度数,数字就会丢失小数点。这是我的尝试(修改后的代码)

I'm trying to save a std::vector<double> to a file and read to rebuild the std::vector<double>. This code from rex (original answer) works for std::vector<char> but not for doubles. Once I tried to modify this to work with doubles, numbers lose decimal points. Here is my attempt (modified code)

#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>

std::string filename("savefile");

std::vector<double> myVector{1321.32132,16.32131,32.321,64,3213.454};

void write_vector_to_file(const std::vector<double>& myVector, std::string filename);
std::vector<double> read_vector_from_file(std::string filename);

int main()
{
    write_vector_to_file(myVector, filename);
    auto newVector{read_vector_from_file(filename)};
    //printing output
    std::cout << newVector.at(1) << std::endl;
    return 0;
}

void write_vector_to_file(const std::vector<double>& myVector,std::string filename)
{
    std::ofstream ofs(filename,std::ios::out | std::ofstream::binary);
    std::ostream_iterator<char> osi{ofs};
    std::copy(myVector.begin(),myVector.end(),osi);
}

std::vector<double> read_vector_from_file(std::string filename)
{
    std::vector<double> newVector{};
    std::ifstream ifs(filename,std::ios::in | std::ifstream::binary);
    std::istreambuf_iterator<char> iter(ifs);
    std::istreambuf_iterator<char> end{};
    std::copy(iter,end,std::back_inserter(newVector));
    return newVector;
}

此代码输出 16 ,而不是 16.32131
我应该怎么做才能使这项功能加倍?
谢谢。

This code outputs 16 instead of 16.32131. What should I do to make this work with doubles? Thank you.

推荐答案

这应该有效:

void write_vector_to_file(const std::vector<double>& myVector, std::string filename)
{
    std::ofstream ofs(filename, std::ios::out | std::ofstream::binary);
    std::ostream_iterator<char> osi{ ofs };
    const char* beginByte = (char*)&myVector[0];

    const char* endByte = (char*)&myVector.back() + sizeof(double);
    std::copy(beginByte, endByte, osi);
}

std::vector<double> read_vector_from_file(std::string filename)
{
    std::vector<char> buffer{};
    std::ifstream ifs(filename, std::ios::in | std::ifstream::binary);
    std::istreambuf_iterator<char> iter(ifs);
    std::istreambuf_iterator<char> end{};
    std::copy(iter, end, std::back_inserter(buffer));
    std::vector<double> newVector(buffer.size() / sizeof(double));
    memcpy(&newVector[0], &buffer[0], buffer.size());
    return newVector;
}

问题是在存储之前被转换为char的位置加倍。

The problem was that doubles where being cast to char before storing.

这篇关于保存并从文件C ++中读取双重向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆