Constructing a vector with istream_iterators(使用 istream_iterators 构造向量)
问题描述
我记得曾经看到一种使用迭代器将整个二进制文件读入向量的巧妙方法.它看起来像这样:
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;
}
这个想法是通过传递指定整个流的输入迭代器来使用 vector
的迭代器范围构造函数.问题是我不确定要为结束迭代器传递什么.
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.
如何为文件末尾创建istream_iterator
?我完全记错了这个成语吗?
How do you create an istream_iterator
for the end of a file? Am I completely misremembering this idiom?
推荐答案
您需要 std::istreambuf_iterator<>
,用于原始输入.std::istream_iterator<>
用于格式化输入.至于文件的结尾,使用流迭代器的默认构造函数.
You want the std::istreambuf_iterator<>
, for raw input. The std::istream_iterator<>
is for formatted input. As for the end of the file, use the stream iterator's default constructor.
std::ifstream source("myfile.dat", std::ios::binary);
std::vector<char> data((std::istreambuf_iterator<char>(source)),
std::istreambuf_iterator<char>());
编辑以满足C++最烦人的解析.谢谢,@UncleBens.
Edited to satisfy C++'s most vexing parse. Thanks, @UncleBens.
这篇关于使用 istream_iterators 构造向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 istream_iterators 构造向量


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01