C++ Iterator














































C++ Iterator



/* Description Class :- Iterator This is a base class template that can be used to derive iterator classes from it. It is not an iterator class and does not provide any of the functionality an iterator is expected to have. This base class only provides some member types, which in fact are not required to be present in any iterator type (iterator types have no specific member requirements), but they might be useful, since they define the members needed for the default iterator_traits class template to generate the appropriate instantiation automatically (and such instantiation is required to be valid for all iterator types). It is defined as: template <class Category, class T, class Distance = ptrdiff_t, class Pointer = T*, class Reference = T&> struct iterator { typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; typedef Category iterator_category; }; */ #include <iostream> #include <iterator> class MyIterator : public std::iterator<std::input_iterator_tag, int> { int* p; public: MyIterator(int* x) :p(x) {} MyIterator(const MyIterator& mit) : p(mit.p) {} MyIterator& operator++() { ++p; return *this; } MyIterator operator++(int) { MyIterator tmp(*this); operator++(); return tmp; } bool operator==(const MyIterator& rhs) const { return p==rhs.p; } bool operator!=(const MyIterator& rhs) const { return p!=rhs.p; } int& operator*() { return *p; } }; int main () { int numbers[]={100,200,300,400,500}; MyIterator from(numbers); MyIterator until(numbers+5); for (MyIterator it=from; it!=until; it++) std::cout << *it << ' '; std::cout << '\n'; return 0; } /* Output:- 100 200 300 400 500 */

Comments