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讀取的輸入迭代器 (類模板) |