Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <iterator>
- template <class _Ty, class _Elem = char, class _Traits = std::char_traits<_Elem>, class _Diff = std::ptrdiff_t>
- class Itr
- { // wrap _Ty extracts from input stream as input iterator
- public:
- using iterator_category = std::input_iterator_tag;
- using value_type = _Ty;
- using difference_type = _Diff;
- using pointer = const _Ty*;
- using reference = const _Ty &;
- using char_type = _Elem;
- using traits_type = _Traits;
- using istream_type = std::basic_istream<_Elem, _Traits>;
- constexpr Itr() : _Myistr(nullptr), _Myval() { // construct singular iterator
- }
- Itr(istream_type& _Istr) : _Myistr(std::addressof(_Istr)) { // construct with input stream
- _Getval();
- }
- const _Ty& operator*() const {
- return _Myval;
- }
- const _Ty* operator->() const {
- return std::addressof(_Myval);
- }
- Itr& operator++() {
- _Getval();
- return *this;
- }
- Itr operator++(int) {
- auto _Tmp = *this;
- _Getval();
- return _Tmp;
- }
- bool _Equal(const Itr& _Right) const {
- return _Myistr == _Right._Myistr;
- }
- protected:
- void _Getval() { // get a _Ty value if possible
- if (_Myistr)
- {
- while (!(*_Myistr >> _Myval))
- {
- if (_Myistr->eof())
- {
- _Myistr = nullptr;
- break;
- }
- else
- {
- _Myistr->clear();
- _Myistr->get();
- }
- }
- }
- }
- istream_type* _Myistr; // pointer to input stream
- _Ty _Myval; // lookahead value (valid if _Myistr is not null)
- };
- template <class _Ty, class _Elem, class _Traits, class _Diff>
- inline bool operator==(const Itr<_Ty, _Elem, _Traits, _Diff>& _Left,
- const Itr<_Ty, _Elem, _Traits, _Diff>& _Right) { // test for istream_iterator equality
- return _Left._Equal(_Right);
- }
- template <class _Ty, class _Elem, class _Traits, class _Diff>
- inline bool operator!=(const Itr<_Ty, _Elem, _Traits, _Diff>& _Left,
- const Itr<_Ty, _Elem, _Traits, _Diff>& _Right) { // test for istream_iterator inequality
- return !(_Left == _Right);
- }
- void fill_vector(std::istream& ist, std::vector<int>& v)
- {
- std::copy(Itr<int>(ist), Itr<int>(), std::back_inserter(v));
- }
- int main()
- {
- std::vector<int> v;
- fill_vector(std::cin, v);
- std::copy(std::begin(v), std::end(v), std::ostream_iterator<int>(std::cout, ","));
- std::cin.clear();
- std::cin.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement