1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <string> #include <iostream>
using namespace std;
class istream_line_reader { public: class iterator { // 实现 InputIterator public: typedef ptrdiff_t difference_type; typedef string value_type; typedef const value_type* pointer; typedef const value_type& reference; typedef input_iterator_tag iterator_category;
iterator() noexcept : stream_(nullptr) {}
explicit iterator(istream& is) : stream_(&is) { ++*this; }
reference operator*() const noexcept { return line_; }
pointer operator->() const noexcept { return &line_; }
iterator& operator++() { getline(*stream_, line_); if (!*stream_) { stream_ = nullptr; } return *this; }
iterator operator++(int) { iterator temp(*this); ++*this; return temp; }
bool operator==(const iterator& rhs) const noexcept { return stream_ == rhs.stream_; }
bool operator!=(const iterator& rhs) const noexcept { return !operator==(rhs); }
private: istream* stream_; string line_; };
istream_line_reader() noexcept : stream_(nullptr) {}
explicit istream_line_reader(istream& is) noexcept : stream_(&is) {}
iterator begin() { return iterator(*stream_); }
iterator end() const noexcept { return iterator(); }
private: istream* stream_; };
int main() { for (const string& line : istream_line_reader(cin)) { cout << line << endl; }}
|