Pippi
Pippi

Reputation: 2571

How to define the type of a member of an iterator class to work with STL container methods?

I wish to define an iterator class over a vector, and how can its private member p match the return type of std::vector::begin()?

class A{

struct element{
      ...
}

  class e_iterator {

  e_iterator() : p()

    ...

    private:
      element* p;  
  };

  e_iterator e_begin() const{
     e_iterator Iter;
     Iter.p = e_.begin(); // error
     return Iter;
  }

 std::vector<element> e_; 

} I receive an error with element* p:

error: cannot convert 'std::vector<element, std::allocator<element>>::const_iterator' to 'element*' in assignment

Upvotes: 0

Views: 319

Answers (2)

Yggi
Yggi

Reputation: 75

Either change element* p to const element* p in your iterator class or remove the const qualifier from your e_begin() method. Or provide both const/non-const iterator. I also suggest to initialize the pointer in the iterator constructor:

template <bool isconst>
class e_iterator_ {

  public:
    typedef std::conditional<isconst, const element*, element*>::type elementptr;

    e_iterator_(elementptr e) : p(e)

  ...

  private:
    elementptr p;  
};

typedef e_iterator_<true> const_e_iterator;
typedef e_iterator_<false> e_iterator;

Then you could use the data() member method of std::vector to directly access the underlying array of the vector.

  e_iterator e_begin() const{
     const_e_iterator Iter(e_.data());
     return Iter;
  }

Hope this helps.

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110748

With what you've given, the most I can suggest is changing p to:

std::vector<element>::const_iterator p;

The simple fact is that a std::vector iterator is not a pointer (probably). It is an unspecified type that behaves like a pointer - it meets the requirements of a Random Access Iterator.

When you call begin() on a non-const container, you get an iterator type. When you call it on a const iterator, you get a const_iterator type. Since your a_begin member function is marked const and e_ appears to be a std::vector<element> member of your class, e_ is transitively const, so calling begin() on it will also get you a const_iterator.

But it's quite hard to tell exactly what you're trying to do here and whether this is the right way to go about it.

Upvotes: 1

Related Questions