stream iterators源代码详解
?? ?所謂stream iterators,可以將迭代器綁定到一個stream(數據流)對象身上。綁定istream對象(例如:std:cin),稱為 istream_iterator,擁有輸入能力。乍聽之下真神奇。所謂綁定一個istream object,其實就是在istream iterator內部維護一個istream member,客戶端對于這個迭代器所做的operator++操作會導致調用迭代器內部所含的那個istream member的輸入操作(operator>>)。這個迭代器是個input iterator,不具備operator--。下面的源代碼說明了一切:
template <class T,class Distance =ptrdiff_t>
class istream_iterator{
?? ?friend bool;
?? ?operator==_STL_NULL_TMPL_ARGS (const istream_iterator<T,Distance>& x,
?? ??? ??? ??? ??? ??? ??? ? const istream_iterator<T, Distance>& Y);
?? ?protected:
?? ??? ?istream* stream;
?? ??? ?T value;
?? ??? ?bool end_marker;
?? ??? ?void read(){
?? ??? ??? ?end_marker=(*stream)? true : false;
?? ??? ??? ?if(end_marker)
?? ??? ??? ??? ?*stream >> value;
?? ??? ??? ?///以上,輸入之后,stream的狀態可能改變,
???????????????????????/?所以下面再判斷一次以決定?end_marker
?? ??? ??? ?當讀到eof或讀到型別不同的資料,stream即處于false狀態
?? ??? ??? ?end_marker=(*stream) ? true : false;
?? ??? ?}
?? ?public:
?? ??? ?typedef input_iterator_tag?? ??? ?iterator_category;
?? ??? ?typedef T?? ??? ??? ??? ??? ??? ?value_type;
?? ??? ?typedef Distance?? ??? ??? ??? ?difference_type;
?? ??? ?typedef const T*?? ??? ??? ??? ?pointer;
?? ??? ?typedef const T&?? ??? ??? ??? ?reference;
?? ??? ?istream_iterator() : stream(&cin), end_marker(flase) {}
?? ??? ?istream_iterator(istream& s) : stream(&s) {read();}
?? ??? ?以上兩行的代碼的用法:
?? ??? ?/istream_iterator<int> eos;?? 造成end_marker 為 false;
?? ??? ?/istream_iterator<int> initer(cin);?? 引發read(),程序至此會等待輸入
?? ??? ?reference operator*() const {return value; }
?? ??? ?pointer operator->() const {return &operator*(); }
?? ??? ?迭代器每前進一個位置,就代表獨取一筆資料
?? ??? ?istream_iterator<T,Distance>& operator++(){
?? ??? ??? ?read();
?? ??? ??? ?return *this();
?? ??? ?}
?? ??? ?istream_ierator<T,Distance> operator++(int){
?? ??? ??? ?istream_iterator<T,Distance> tmp=*this;
?? ??? ??? ?read();
?? ??? ??? ?return tmp;
?? ??? ?}
};
本原創文章來源:C++技術網 http://www.cjjjs.cn ,原創精品文章,歡迎訪問C++技術網。
轉載于:https://www.cnblogs.com/cjjjs/p/4963516.html
總結
以上是生活随笔為你收集整理的stream iterators源代码详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: weblogic启动受管服务器报错Aut
- 下一篇: C1. 组队活动 Small(BNUOJ