Boost logo

Boost :

From: Dan Eloff (dan.eloff_at_[hidden])
Date: 2004-09-02 02:33:59


If this is my fault the docs need to be more explanatory, but here's
the problem:

for the sequence (0, 1, 2), the Boost::Python iterator starts at 1 and
ends 1 past 2 ( where 3 might be ).

It does this because it calls the C++ iterators functions in this order:

operator ==
post-increment
dereference

It should imho call them like (which would correct the issue)

operator ==
dereference
post-increment

Like a normal for loop would execute: condition, code, action.

The code to reproduce this is:

#include <iterator>

#include <boost/python.hpp>

namespace py = boost::python;

struct ctn
{
        struct iterator: public std::iterator< std::input_iterator_tag, py::str >
        {
                int mNum;

                iterator( int num = 0 ): mNum( num ) {}

                py::str operator *() const
                {
                        char temp[20];
                        const char * str = itoa( mNum, temp, 10 );
                        return py::str( str, strlen( str ) );
                }

                iterator& operator ++(int)
                {
                        mNum++;
                        return *this;
                }

                friend bool operator ==( iterator lhs, iterator rhs )
                {
                        return ( lhs.mNum == rhs.mNum );
                }
        };

        iterator begin()
        {
                return iterator( 0 );
        }

        iterator end()
        {
                return iterator( 3 ); // the range (0, 1, 2) three items
        }
};

BOOST_PYTHON_MODULE(iter_bug)
{
        py::class_< ctn >( "ctn" )
                .def( "__iter__", py::iterator< ctn >() )
                ;
}

>>> from iter_bug import *
>>> c = ctn()
>>> for i in c:
... print i
...
1
2
3
>>>

Notice how it's off by one because of the very strange order of doing
things. Please help!

-Dan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk