有一个问题在精神上很相似here https://stackoverflow.com/questions/2476425/c-stl-stdtransform-with-given-stride。不幸的是,这个问题没有引起太多回应 - 我想我会问一个更具体的问题,希望可以建议替代方法。
我正在将二进制文件写入std::cin
(with tar --to-command=./myprog
)。
二进制文件恰好是一组浮点数,我想将数据放入std::vector<float>
- 最好是 C++ 方式。
我可以生成一个std::vector<char>
非常好(感谢这个答案 https://stackoverflow.com/questions/5420317/c-reading-and-writing-binary-file/5420568#5420568)
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
int
main (int ac, char **av)
{
std::istream& input = std::cin;
std::vector<char> buffer;
std::copy(
std::istreambuf_iterator<char>(input),
std::istreambuf_iterator<char>( ),
std::back_inserter(buffer)); // copies all data into buffer
}
我现在想改变我的std::vector<char>
into a std::vector<float>
,大概与std::transform
和一个执行转换的函数(achar[2]
to a float
, 说)。然而我正在挣扎,因为我的std::vector<float>
将有一半的元素std::vector<char>
。如果我可以以 2 的步幅进行迭代,那么我想我会很好,但从上一个问题来看,我似乎无法做到这一点(至少不能优雅地做到)。
我会编写自己的类来读取两个字符并将其转换为浮点数。
struct FloatConverter
{
// When the FloatConverter object is assigned to a float value
// i.e. When put into the vector<float> this method will be called
// to convert the object into a float.
operator float() { return 1.0; /* How you convert the 2 chars */ }
friend std::istream& operator>>(std::istream& st, FloatConverter& fc)
{
// You were not exactly clear on what should be read in.
// So I went pedantic and made sure we just read 2 characters.
fc.data[0] = str.get();
fc.data[1] = str.get();
retun str;
}
char data[2];
};
根据 GMan 的评论:
struct FloatConverterFromBinary
{
// When the FloatConverterFromBinary object is assigned to a float value
// i.e. When put into the vector<float> this method will be called
// to convert the object into a float.
operator float() { return data }
friend std::istream& operator>>(std::istream& st, FloatConverterFromBinary& fc)
{
// Use reinterpret_cast to emphasis how dangerous and unportable this is.
str.read(reinterpret_cast<char*>(&fc.data), sizeof(float));
retun str;
}
float data;
};
然后像这样使用它:
int main (int ac, char **av)
{
std::istream& input = std::cin;
std::vector<float> buffer;
// Note: Because the FloatConverter does not drop whitespace while reading
// You can potentially use std::istream_iterator<>
//
std::copy(
std::istreambuf_iterator<FloatConverter>(input),
std::istreambuf_iterator<FloatConverter>( ),
std::back_inserter(buffer));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)