Boost logo

Boost :

From: Keith MacDonald (boost_at_[hidden])
Date: 2003-09-28 12:21:40


I couldn't find an example of how to add iterators to a new container class,
so have created one myself. However, I'd appreciate some advice on how to
implement the non-const iterator. I've got a very simple container, with
embedded classes for const_iterator, derived from iterator_adaptor, and
iterator, derived from const_iterator. The iterator_adaptor Base is an
unsigned char*, so I only had to implement constructors for const_iterator.
However, I found that I also needed to implement operator* for iterator,
otherwise constructs like "*it = 'x';" failed with "l-value specifies const
object".

In the code that follows. Have I used iterator_adaptor in the best way,
and do I really need to override operator* for the non-const iterator?

Thanks,
Keith MacDonald

[code]

// Using iterator_adaptor.hpp dated 20th July with VC.Net 2003.
#include <boost/iterator/iterator_adaptor.hpp>

class container2
{
public:
    class const_iterator;

    typedef boost::iterator_adaptor<const_iterator,
                                    const unsigned char*,
                                    const unsigned char,
                                    boost::random_access_traversal_tag
> boost_const_iterator;

    class const_iterator
        : public boost_const_iterator
    {
    public:
        const_iterator()
            : boost_const_iterator(NULL)
        {}

        const_iterator(const unsigned char* p)
            : boost_const_iterator(p)
        {}
    };

    class iterator
        : public const_iterator
    {
    public:
        iterator()
            : const_iterator(NULL)
        {}

        iterator(unsigned char* p)
            : const_iterator(p)
        {}

        unsigned char& operator*()
        {
            return const_cast<unsigned char&>(*base_reference());
        }
    };

public:

    container2()
    {
        for (int i = 0; i < sizeof(buffer); ++i)
            buffer[i] = i;
    }

    const_iterator begin() const
    {
        return const_iterator(buffer);
    }

    const_iterator end() const
    {
        return const_iterator(buffer + sizeof(buffer));
    }

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

    iterator end()
    {
        return iterator(buffer + sizeof(buffer));
    }

private:
    unsigned char buffer[256];
};

[/code]


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