stream iterators源代码详解
?? ?所謂stream iterators,可以將迭代器綁定到一個(gè)stream(數(shù)據(jù)流)對象身上。綁定istream對象(例如:std:cin),稱為 istream_iterator,擁有輸入能力。乍聽之下真神奇。所謂綁定一個(gè)istream object,其實(shí)就是在istream iterator內(nèi)部維護(hù)一個(gè)istream member,客戶端對于這個(gè)迭代器所做的operator++操作會導(dǎo)致調(diào)用迭代器內(nèi)部所含的那個(gè)istream member的輸入操作(operator>>)。這個(gè)迭代器是個(gè)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的狀態(tài)可能改變,
???????????????????????/?所以下面再判斷一次以決定?end_marker
?? ??? ??? ?當(dāng)讀到eof或讀到型別不同的資料,stream即處于false狀態(tài)
?? ??? ??? ?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);?? 引發(fā)read(),程序至此會等待輸入
?? ??? ?reference operator*() const {return value; }
?? ??? ?pointer operator->() const {return &operator*(); }
?? ??? ?迭代器每前進(jìn)一個(gè)位置,就代表獨(dú)取一筆資料
?? ??? ?istream_iterator<T,Distance>& operator++(){
?? ??? ??? ?read();
?? ??? ??? ?return *this();
?? ??? ?}
?? ??? ?istream_ierator<T,Distance> operator++(int){
?? ??? ??? ?istream_iterator<T,Distance> tmp=*this;
?? ??? ??? ?read();
?? ??? ??? ?return tmp;
?? ??? ?}
};
本原創(chuàng)文章來源:C++技術(shù)網(wǎng) http://www.cjjjs.cn ,原創(chuàng)精品文章,歡迎訪問C++技術(shù)網(wǎng)。
轉(zhuǎn)載于:https://www.cnblogs.com/cjjjs/p/4963516.html
總結(jié)
以上是生活随笔為你收集整理的stream iterators源代码详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: weblogic启动受管服务器报错Aut
- 下一篇: C1. 组队活动 Small(BNUOJ