Boost logo

Boost Users :

From: Ben Hutchings (ben.hutchings_at_[hidden])
Date: 2003-04-11 10:08:31


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<class IteratorAdaptor, class DifferenceType>
> 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;


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net