我需要将一个大的二进制文件(〜1GB)读入std::vector<double>。我目前正在使用infile.read将整个内容复制到char *缓冲区(如下所示)中,并且我目前计划使用doubles将整个内容转换为reinterpret_cast。肯定有一种方法可以将doubles直接放入vector吗?

我也不确定二进制文件的格式,数据是在python中产生的,因此可能是所有浮点数

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/

10-12 00:02
查看更多