`istreambuf_iterator`和`istream_iterator`之间的区别

`istreambuf_iterator`和`istream_iterator`之间的区别

问题描述:

  1. istreambuf_iterator istream_iterator 之间有什么区别.

对于以下代码:

 istream_iterator<int> cin_in(cin);
 istream_iterator<int> end; 

迭代器 end 指向何处?
迭代器会与流绑定吗?
如果我写代码

where does the iterator end point to?
Will the iterator bind with the stream?
If I write the code

istream_iterator<int>()

end 相同吗?

所有文件都记录在哪里?

And where is that all documented?

istreambuf_iterator istream_iterator 之间有什么区别.

std :: istream_iterator 是用于格式化提取的迭代器.例如,如果文件中有一行整数并希望将它们复制到某个容器中,则可以使用 std :: istream_iterator< int> ,它会在内部复制从中提取的值> int (使用 operator>>>())到容器:

std::istream_iterator is an iterator for formatted extraction. For instance, if you have a line of integers from a file and wish to copy them to some container, you would use std::istream_iterator<int> which internally will copy the value extracted from an int (using operator>>()) to the container:

std::copy(std::istream_iterator<int>(file),
          std::istream_iterator<int>(), std::back_inserter(some_container));

std :: istreambuf_iterator 是用于无格式提取的迭代器.它直接在通过其构造函数提供的 std :: streambuf 对象上工作.这样,如果您只需要文件的内容而不用担心它们的格式,请使用此迭代器.例如,有时您想将整个文件读入字符串或某个容器中.常规格式的提取器将舍弃前导空格并转换提取的令牌;缓冲区迭代器不会:

std::istreambuf_iterator is an iterator for unformatted extraction. It works directly on the std::streambuf object provided through its constructor. As such, if you need simply the contents of the file without worrying about their format, use this iterator. For example, sometimes you want to read an entire file into a string or some container. A regular formatted extractor will discard leading whitespace and convert extracted tokens; the buffer iterator will not:

std::string str(std::istreambuf_iterator<char>{file}, {});

迭代器的终点指向哪里?

Where does the iterator end point to?

默认构造的流迭代器只是一个特殊的哨兵对象,它代表流的结尾.由于IOStreams是单次通过的,因此在我们阅读完该点之前,它无法真正指向末尾.在内部,当提取失败或读取命中文件末尾时,使用流(或流缓冲区)构造的迭代器将变为最终流迭代器.这就是标准算法与流迭代器一起使用的原因,因为它们的作用类似于外部的常规迭代器.

A default-constructed stream iterator is simply a special sentinel object that represents the end of the stream. Since IOStreams are one-pass, there's no way for it to actually point to the end until we have read up to that point. Internally, when an extraction has failed or the read hit the end-of-file, the iterator that was constructed with a stream (or stream buffer) will change into an end stream iterator. This is what helps standard algorithms work with stream iterators, since they act like regular iterators on the outside.

所有文件都记录在哪里?

And where is that all documented?

很多地方.正式在标准中.您还可以在 cppreference 上找到文档.

Many places. Formally in the Standard. You can also find documentation on cppreference.