
Olaf Petzold wrote:
I try to write a cyclic Iterator using boost::iterator_adaptors. Unfortunally, the advance function doesn't work for negative distances correct:
template<class Iterator> class cycle_iterator_policies { public: cycle_iterator_policies(const Iterator& begin, const Iterator& end) : m_begin( begin ), m_end( end ) { assert( m_begin != m_end ); } .... template
void advance( IteratorAdaptor& x, DifferenceType n ) { n %= std::distance( m_begin, m_end ); <snip>
The problem is that the result of % and / (and by implication %= and /=) is implementation defined if either operand is negative. Most implementations round the quotient towards zero and produce a remainder with the same sign as the quotient. Evidently you want to have a non-negative remainder always. The simplest solution, I think, is: DifferenceType length = std::distance( m_begin, m_end ); n %= length; if (n < 0) n += length;