如何有效地将二进制文件读入矢量C++

Aar*_*ear 9 c++ binary file stdvector

我需要读一个大的二进制文件(~1GB)std::vector<double>.我目前正在使用infile.read将整个事物复制到char *缓冲区(如下所示),我目前正计划将整个事物转换doublesreinterpret_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);
Run Code Online (Sandbox Code Playgroud)

Ton*_*y J 9

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

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
Run Code Online (Sandbox Code Playgroud)

  • @AlanStokes @TonyJiang因为`std :: array`是(按设计)C数组的零开销包装器(`int arr [100];`kind).那些最终在堆栈上(除非它具有"静态"存储持续时间或动态分配,但在这种情况下不执行后者). (4认同)
  • @BaummitAugen好奇,为什么std :: array不适合大数据?堆栈上的存储空间是什么? (2认同)