简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM