使用 istream_iterators 构造向量

2021-12-21 00:00:00 iterator vector c++ stl

我记得曾经看到一种使用迭代器将整个二进制文件读入向量的巧妙方法.它看起来像这样:

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.

相关文章