使用 istream_iterators 构造向量
我记得曾经看到过一种使用迭代器将整个二进制文件读入向量的巧妙方法。它看起来像这样:
#include <fstream>
#include <ios>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ifstream source("myfile.dat", ios::in | ios::binary);
vector<char> data(istream_iterator(source), ???);
// do stuff with data
return 0;
}
这个想法是通过传递指定整个流的输入迭代器来使用向量的迭代器范围构造函数。问题是我不确定要为结束迭代器传递什么。
如何为文件末尾创建一个istream_iterator
?我完全记错了这个成语吗?
I recall once seeing a clever way of using iterators to read an entire binary file into a vector. It looked something like this:
#include <fstream>
#include <ios>
#include <iostream>
#include <vector>
using namespace std;
int main() {
ifstream source("myfile.dat", ios::in | ios::binary);
vector<char> data(istream_iterator(source), ???);
// do stuff with data
return 0;
}
The idea is to use vector
's iterator range constructor by passing input iterators that specify the entire stream. The problem is I'm not sure what to pass for the end iterator.
How do you create an istream_iterator
for the end of a file? Am I completely misremembering this idiom?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
std::istreambuf_iterator
作为原始输入。std::istream_iterator
用于格式化输入。至于文件末尾,使用流迭代器的默认构造函数。编辑以满足C++ 最令人烦恼的解析。谢谢,@UncleBens。
You want the
std::istreambuf_iterator<>
, for raw input. Thestd::istream_iterator<>
is for formatted input. As for the end of the file, use the stream iterator's default constructor.Edited to satisfy C++'s most vexing parse. Thanks, @UncleBens.
在 C++11 中,可以:
这种较短的形式避免了由于
{}
参数而导致的最棘手的解析问题,这消除了它是参数还是形式参数的歧义。@wilhelmtell 的答案也可以通过对
data
采用大括号初始值设定项来更新,以避免此问题。仍然在我看来,使用{}
更简单,并且使初始化形式变得无关紧要。编辑
或者,如果我们有
std::lvalue
(也许还有std:: xvalue
而不是std::move
):In C++11 one could:
This shorter form avoids the most vexing parse problem because of the
{}
argument, which removes ambiguity of it being an argument or a formal parameter.@wilhelmtell's answer could also be updated to avoid this problem by adopting a brace initializer for
data
. Still in my view, using{}
is more simple and turn the initialization form irrelevant.EDIT
Or, if we had
std::lvalue
(and maybestd::xvalue
instead ofstd::move
):