Search code examples
c++stliterator

Can std::iterator check, if the next element exist over that iterator? ( This design is restricted by a HOMEWORK)


I have a template Iterator class that contains std::iterator of container that is specified by template. I did not find any way to check if the next element exist over the iterator, without using container.

There is a control like this;

vector<int> v; 
vector<int>::iterator itr;
if(itr== v.end()) { /*...*/}

but I wanted to do this control in my Iterator class and my class is like following...

  template <class E, class C= vector<E> >
  class Iterator {
  public:
    /*...*/
    bool hasNext()noexcept; 
    /*...*/
  private:
    typename C::iterator itr; // is there any problem with this decleration?
  };

  //implementation of hasNext() function.
  template<class E, class C>
  bool
  Iterator<E,C>::hasNext()noexcept {
    return(itr!=end())?true:false; // this line is wrong. How can I fix it?
  }

Solution

  • An iterator represents a position within a sequence of items. An iterator knows how to get to the next element in that sequence, but the nature of C++'s iterator model is based on the idea that there exists a "past-the-end" iterator after the end of such a sequence. Such an iterator does not represent a valid item in the sequence; it merely represents the end of the sequence, and iterators can be tested against it.

    This construct is useful, as it allows you to talk about sub-ranges of elements within a sequence. For example, if a container has 10 elements, you can pass the begin/end iterators to the std::sort algorithm to sort them. However, you could also sort the first 10 elements by passing the begin iterator and the begin() + 10 iterator to the same function. The sort algorithm will treat the given ending iterator as the "past-the-end" iterator, not an iterator to a valid element.

    What you are trying to do is combine two distinct ideas: position and range. Some iteration models do things that way, but that is not the STL-derived model that C++'s standard library is based on.

    Now to be fair, there are some cases where position inherently carries range information. stream-based iterators know whether they are at the end of the stream or not, because to function as an iterator, they have to store a reference to the stream they iterate over. And the stream knows whether it is out of data. But overall, a single iterator is not meant to know whether it is at the end of its range or not.