# HG changeset patch # User Eris Caffee # Date 1435097649 18000 # Node ID 80ca1973e3bdccd2e5ec37f5cfd8f1a08652ce40 # Parent 2cbfacd2a3e986c2c8bb97bc612637c94470bb71 Fleshed out Queue::generic_iterator a bit more to make it a more or less complete example of implmenting an iterator. diff -r 2cbfacd2a3e9 -r 80ca1973e3bd algs4-c++/src/Queue.cpp --- a/algs4-c++/src/Queue.cpp Tue Jun 23 15:46:22 2015 -0500 +++ b/algs4-c++/src/Queue.cpp Tue Jun 23 17:14:09 2015 -0500 @@ -2,6 +2,7 @@ #include +#include #include "Queue.hpp" @@ -31,6 +32,9 @@ std::cout << *iter << std::endl; } + // Just make sure that we can build an iterator with the copy constructor. + auto iter = q2.begin(); + auto iter2( iter ); std::cout << "Dequeuing entries..." << std::endl; @@ -45,5 +49,18 @@ // Silently empty q2 to avoid the assertion in the destructor. while ( ! q2.is_empty() ) q2.dequeue(); + + // Show the iterator traits; + std::cout << std::endl; + if ( typeid( Queue::iterator_traits::iterator_category) == typeid( std::forward_iterator_tag ) ) + std::cout << "category: forward iterator" << std::endl;; + if ( typeid( Queue::iterator_traits::value_type) == typeid( long ) ) + std::cout << "value_type: long" << std::endl;; + if ( typeid( Queue::iterator_traits::pointer) == typeid( long * ) ) + std::cout << "pointer: long *" << std::endl;; + if ( typeid( Queue::iterator_traits::reference) == typeid( long & ) ) + std::cout << "reference: long &" << std::endl;; + if ( typeid( Queue::iterator_traits::difference_type ) == typeid( ptrdiff_t ) ) + std::cout << "difference_type: ptrdiff_t" << std::endl;; } diff -r 2cbfacd2a3e9 -r 80ca1973e3bd algs4-c++/src/Queue.hpp --- a/algs4-c++/src/Queue.hpp Tue Jun 23 15:46:22 2015 -0500 +++ b/algs4-c++/src/Queue.hpp Tue Jun 23 17:14:09 2015 -0500 @@ -38,6 +38,11 @@ { } + generic_iterator( const generic_iterator& other ) : + curr (other.curr) + { + } + generic_iterator & operator++() { if ( this->curr != nullptr ) { this->curr = this->curr->next; @@ -58,8 +63,12 @@ return this->curr->item; } - bool operator!=( generic_iterator other ) { - return this->curr != other.curr; + bool operator==( generic_iterator rhs ) { + return this->curr == rhs.curr; + } + + bool operator!=( generic_iterator rhs ) { + return this->curr != rhs.curr; } private: @@ -71,6 +80,7 @@ typedef generic_iterator const_iterator; typedef generic_iterator iterator; + typedef std::iterator_traits< generic_iterator<> > iterator_traits; Queue( void ); ~Queue( void );