有没有办法更有效地将二进制双精度从文件读取到浮点数组中

Is there a way to more efficiently read binary doubles from file into an array of floats?

本文关键字:读取 文件 数组 双精度 有效地 二进制 有没有      更新时间:2023-10-16

有没有比这样明显的解决方案更好的方法来从文件中读取二进制双精度并最终将值放入浮点数向量中?

    vector< double > dv( N );
    ifstream inFile( path ); 
    inFile.read( ( char* ) dv.data(), N*sizeof( double ) );
    inFile.close();
    vector< float > fv( dv.begin(), dv.end() ); 

您根本不需要单独的std::vector<double>

您可以使用手动读取循环:

std::vector<float> fv; 
fv.reserve(N);
std::ifstream inFile(path); 
double d;
while (inFile.read((char*)&d, sizeof(d)))
    fv.push_back(static_cast<float>(d));
inFile.close();

或者,您可以使用std::istream_iterator直接从std::ifstream填充std::vector<float>

class readDoubleToFloat {
    double data;
public:
    friend std::istream& operator>>(std::istream &is, readDoubleToFloat &val) {
        is.read((char*)&(val.data), sizeof(double));
        return is;
    }
    operator float() const { return static_cast<float>(data); }    
};
std::ifstream inFile(path); 
std::vector<float> fv; 
fv.reserve(N);
std::copy(
    std::istream_iterator<readDoubleToFloat>(inFile),
    std::istream_iterator<readDoubleToFloat>(),
    std::back_inserter(fv));
inFile.close();