Do null iterators damage undefined behavior?

using namespace std;
class myList
{
  public:
    mylist():_internalList(),_lastPostition(0)
  {
  }
    typedef list<string>::iterator Itr;
    bool enqueue(string);
    Itr next()
    {
      if(_lastPostition == 0)
        _lastPostition = _internalList.begin();
      if(_lastPostition == _internalList.end())
        return (_lastPostition = 0);
      return _lastPostition++;
    }
  private:
    list<string> _internalList;
    Itr _lastPostition;
}

enqueueno push_back, it inserts based on some user logic. I cannot use std::setand overload operator <, because my insertion logic is not transitive - it ( a < b && b < c)does not mean a < c.

This works, but I'm not sure its behavior is undefined. Is it safe to assign 0 to an iterator and check for 0?

+3
source share
3 answers

"Is it safe to assign 0 to an iterator and check for 0?" No.

+4
source

You cannot assign 0 to an iterator, you need to use another special value, for example end().

0
source

next, , has_next(), , .

Itr next()
{
   if ( !has_next() )
       _lastPostition = _internalList.begin();
   return ++_lastPostition;
}
bool has_next() const
{
   Itr  temp = lastPostition;
   return (++temp== _internalList.end());
}

: next() ; , , !

0

All Articles