gpt4 book ai didi

c++ - 如何有效地将二进制文件读入 vector C++

转载 作者:可可西里 更新时间:2023-11-01 16:37:29 25 4
gpt4 key购买 nike

我需要将一个大的二进制文件 (~1GB) 读入 std::vector<double> .我目前正在使用 infile.read将整个内容复制到 char *缓冲区(如下所示),我目前计划将整个东西转换成 doublesreinterpret_cast .肯定有办法把 doubles直接进入vector

我也不确定二进制文件的格式,数据是用 python 生成的,所以它可能都是 float

ifstream infile(filename, std--ifstream--binary);

infile.seekg(0, infile.end); //N is the total number of doubles
N = infile.tellg();
infile.seekg(0, infile.beg);

char * buffer = new char[N];

infile.read(buffer, N);

最佳答案

假设整个文件是双重的,否则这将无法正常工作。

std::vector<double> buf(N / sizeof(double));// reserve space for N/8 doubles
infile.read(reinterpret_cast<char*>(buf.data()), buf.size()*sizeof(double)); // or &buf[0] for C++98

关于c++ - 如何有效地将二进制文件读入 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28707928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com