Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an iterator be "automatically dereferenced"?

Suppose I have something like this:

class Collection
{
private:
    typedef std::vector< std::shared_ptr<Something> >::iterator Iterator;
    std::vector< std::shared_ptr<Something> > data_;

public:
    Iterator begin() {return data_.begin()}
    Iterator end()  {return data_.end()}
}

When I use a Collection::Iterator instance I need to dereference it once, to get the std::shared_ptr<Something> object and once again to get Something object.

But if I want to make the std::shared_ptr<Something> just an implementation detail, it is reasonable that after one dereferencing, I should get a Something object.

That is:

Collection collection;
Collection::Iterator it = collection.begin();
Something firstMember = *it;  // instead of the current **it;

My question is, do I need to make the Iterator as a nested class of Collection from scratch and implement all the functions required for a random access iterator from here http://www.cplusplus.com/reference/std/iterator/ or is there some well known approach? Possibly C++11?

like image 447
Martin Drozdik Avatar asked Dec 27 '22 21:12

Martin Drozdik


1 Answers

It sounds like what you're implementing exists and is called boost::ptr_vector. Boost also provides a library for implementing iterators with less pain. It sounds like what you're looking for is boost::indirect_iterator

like image 180
Anton Golov Avatar answered Jan 10 '23 03:01

Anton Golov