我记得曾经看到一种使用迭代器将整个二进制文件读入向量的巧妙方法.它看起来像这样:
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 构造向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)