如何迭代到较小的容器(即步幅!= 1)
此处有一个在精神上非常相似的问题。不幸的是,这个问题没有引起太多回应 - 我想我会问一个更具体的问题,希望可以建议替代方法。
我正在将二进制文件写入 std::cin
(使用 tar --to-command=./myprog
)。 二进制文件恰好是一组浮点数,我想将数据放入 std::vector
- 最好是 C++ 方式。
我可以很好地生成 std::vector
(感谢 这个答案)
#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
转换为 std::vector
,大概是用 std::transform
和一个执行转换的函数(例如,从 char[2]
到 float
)。然而,我很挣扎,因为我的 std::vector
的元素数量是 std::vector
的一半。如果我能以 2 的步幅进行迭代,那么我想我会很好,但从上一个问题来看,我似乎无法做到这一点(至少不能优雅地做到)。
There is a question that is very similar in spirit here. Unfortunately that question didn't prompt much response - I thought I would ask a more specific question with the hope that an alternative method can be suggested.
I'm writing a binary file into std::cin
(with tar --to-command=./myprog
).
The binary file happens to be a set of floats and I want to put the data into std::vector<float>
- ideally the c++ way.
I can generate a std::vector<char>
very nicely (thanks to this answer)
#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
}
I now want to transform my std::vector<char>
into a std::vector<float>
, presumably with std::transform
and a function that does the conversion (a char[2]
to a float
, say). I am struggling however, because my std::vector<float>
will have half as many elements as std::vector<char>
. If I could iterate with a stride of 2 then I think I would be fine, but from the previous question it seems that I cannot do that (at least not elegantly).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会编写自己的类来读取两个字符并将其转换为浮点数。
根据 GMan 的评论:
然后像这样使用它:
I would write my own class that reads two chars and converts it to float.
Based on comments by GMan:
Then use it like this:
在我看来,最好的答案是编写一对您自己的迭代器,以您想要的方式解析文件。您可以将
std::vector
更改为std::vector
并使用相同的streambuf
迭代器(前提是输入已格式化)值之间至少有一个空格。It seems to me that the best answer is to write a pair of your own iterators that parse the file the way that you want. You could change
std::vector<char>
tostd::vector<float>
and use the samestreambuf
iterators provided the input was formatted with at least one space between values.使用boost范围适配器:
您可能需要编写自己的
istreambuf_iterator
,即微不足道。use boost range adaptors:
you might need to write your own
istreambuf_iterator
, which is trivial.