I was reading this trying to figure out how to implement the decrement operator (because I'm guessing I need the bidirectional_iterator) for the circular_iterator template class but it's not working.
The increment operator seems to work fine but when I use decrement it complains.
Here's what main looks like:
Code:
int main(){
list<int> *m_list;
m_list = new list<int>();
for( int i = 0; i < 10; i++ )
m_list->push_back( i+1 );
circular_list_iterator<int> it = m_list;
for(; it != circular_list_end( m_list ); --it) // Complains here (main.cpp line 42)
std::cout << *it << endl;
return 0;
}
Here's the header for circular_list_iterator:
Code:
template<typename T>
class circular_list_iterator : public std::iterator<std::bidirectional_iterator_tag, T>{
public:
circular_list_iterator( std::list<T>* container )
: container( container ), iter( container->begin() ) {}
circular_list_iterator( std::list<T>* container, typename std::list<T>::iterator iter )
: container( container ), iter( iter ) {}
circular_list_iterator& operator++(){
if ( iter != container->end() )
++iter;
else
iter = container->begin();
return *this;
}
circular_list_iterator& operator--(){
if ( iter != container->rend() ) // circ_iter.h line 32
--iter;
else
iter = container->rbegin(); // circ_iter.h line 35
return *this;
}
T& operator*(){ return *iter; }
bool operator!=( circular_list_iterator rhs ) const { return iter != rhs.iter; }
private:
std::list<T>* container;
typename std::list<T>::iterator iter;
};
template<typename T>
circular_list_iterator<T> circular_list_end( std::list<T>* container ){
return circular_list_iterator<T>( container, container->end() );
}
Here's what g++ has to say about all this:
Code:
circ_iter.h: In member function ‘circular_list_iterator<T>& circular_list_iterator<T>::operator--() [with T = int]’:
main.cpp:42: instantiated from here
circ_iter.h:32: error: no match for ‘operator!=’ in ‘((circular_list_iterator<int>*)this)->circular_list_iterator<int>::iter != std::list<_Tp, _Alloc>::rend() [with _Tp = int, _Alloc = std::allocator<int>]()’
/usr/include/c++/4.1.3/bits/stl_list.h:173: note: candidates are: bool std::_List_iterator<_Tp>::operator!=(const std::_List_iterator<_Tp>&) const [with _Tp = int]
main.cpp:42: instantiated from here
circ_iter.h:35: error: no match for ‘operator=’ in ‘((circular_list_iterator<int>*)this)->circular_list_iterator<int>::iter = std::list<_Tp, _Alloc>::rbegin() [with _Tp = int, _Alloc = std::allocator<int>]()’
/usr/include/c++/4.1.3/bits/stl_list.h:112: note: candidates are: std::_List_iterator<int>& std::_List_iterator<int>::operator=(const std::_List_iterator<int>&)
make: *** [main.o] Error 1
So is the problem with rend() and rbegin()? Is it with the iterator category I've inherited? Also, with the use of the pointer to the container, is the inheritance even necessary?