std::istreambuf_iterator
定义于头文件 <iterator> |
||
template< class CharT, class Traits = std::char_traits<CharT> > class istreambuf_iterator |
(C++17 前) | |
template< class CharT, class Traits = std::char_traits<CharT> > class istreambuf_iterator; |
(C++17 起) | |
std::istreambuf_iterator
是一个单通道输入迭代器,它从为其构造的 std::basic_streambuf 对象中读取连续字符。
默认构造的 std::istreambuf_iterator
被称为 流末尾 迭代器。当 std::istreambuf_iterator
到达底层流的末尾时,它变得等于流末尾迭代器。对其进行解引用或进一步递增会导致未定义行为。
|
(C++11 起) |
目录 |
[编辑] 成员类型
成员类型 | 定义 |
iterator_category
|
std::input_iterator_tag |
value_type
|
CharT |
difference_type
|
typename Traits::off_type |
pointer
|
/* 未指定 */ |
reference
|
CharT |
char_type
|
CharT
|
traits_type
|
特性
|
int_type
|
typename Traits::int_type |
streambuf_type
|
std::basic_streambuf<CharT, Traits> |
istream_type
|
std::basic_istream<CharT, Traits> |
/* 代理 */
|
实现定义的类类型。 一个 代理 对象包含一个 char_type 字符和一个 streambuf_type* 指针。使用 operator* 解引用 代理 对象会产生存储的字符。(仅供说明的成员类型*) |
成员类型 |
(C++17 前) |
成员类型 pointer
通常是 CharT*
(参见下方)。
[编辑] 成员函数
构造一个新的 istreambuf_iterator (public member function) | |
(析构函数) (隐式声明) |
析构一个 istreambuf_iterator (public member function) |
获取当前字符的副本 (public member function) | |
前进迭代器 (public member function) | |
测试两个 istreambuf_iterator 是流末尾还是都有效(public member function) |
[编辑] 非成员函数
(在 C++20 中移除) |
比较两个 istreambuf_iterator (function template) |
[编辑] 注意
LWG issue 659 的解决引入了 operator->。期望对于给定的 std::istreambuf_iterator
i,表达式 (*i).m 和 i->m 具有相同的效果。
然而,该解决方案并未提供其行为的正式规范。因此,它的实现方式有所不同,包括返回 nullptr,返回临时变量的地址,甚至根本不提供该成员。其预期行为很难实现,并且已被 LWG issue 2790 的解决方案移除。
LWG issue 659 的解决方案也使成员类型 pointer
未指定,以便允许 operator->
返回代理。这是为了允许在 CharT
不是类类型时,operator->
能够编译。
[编辑] 示例
#include <iostream> #include <iterator> #include <sstream> #include <string> int main() { // typical use case: an input stream represented as a pair of iterators std::istringstream in{"Hello, world"}; std::istreambuf_iterator<char> it{in}, end; std::string ss{it, end}; std::cout << "ss has " << ss.size() << " bytes; " "it holds \"" << ss << "\"\n"; // demonstration of the single-pass nature std::istringstream s{"abc"}; std::istreambuf_iterator<char> i1{s}, i2{s}; std::cout << "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; ++i1; std::cout << "after incrementing i1, but not i2:\n" "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; ++i2; std::cout << "after incrementing i2, but not i1:\n" "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; }
输出
ss has 12 bytes; it holds "Hello, world" i1 returns 'a' i2 returns 'a' after incrementing i1, but not i2: i1 returns 'b' i2 returns 'b' after incrementing i2, but not i1: i1 returns 'c' i2 returns 'c'
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 659 | C++98 | 1. std::istreambuf_iterator 没有 operator->2. 成员类型 pointer 被指定为 CharT* |
1. 添加 2. 更改为未指定 |
LWG 2790 | C++98 | 由 LWG issue 659 添加的 operator-> 没有用处 | 已移除 |
[编辑] 参见
写入std::basic_streambuf的输出迭代器 (类模板) | |
从std::basic_istream读取的输入迭代器 (类模板) |