有没有办法更有效地将二进制双精度从文件读取到浮点数组中
Is there a way to more efficiently read binary doubles from file into an array of floats?
有没有比这样明显的解决方案更好的方法来从文件中读取二进制双精度并最终将值放入浮点数向量中?
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();
相关文章:
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 读取文件的最后一行并输入到链接列表时出错
- 为什么在读取文件大小时文件IO速度会发生变化
- 读取文件时运行时的未知行为
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C++ 读取文件读取文件不正确
- 读取文件并将其存储在unordered_map中时出现问题
- 读取文件时无法使用 OpenMP 获得加速
- 使用istringstearm和get行缓慢读取文件
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 读取文件时引发异常
- 从标准输入读取文件后读取用户输入
- 在读取文件后重置句柄
- 如何在C++编译时读取文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 读取文件在第二次调用时返回INVALID_HANDLE
- 通过指针读取文件
- 逐行读取文件,并将数据插入变量和数组中