Will null iterators cause undefined behaviour?
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开发者_如何学C++;
}
private:
list<string> _internalList;
Itr _lastPostition;
}
enqueue
is not push_back
, it inserts based on some custom logic.
I can't use std::set
and overload operator <
, because my insertion logic isn't transitive - ( a < b && b < c)
does not imply a < c
.
This works but I'm not sure if its an undefined behavior. Is it safe to assign 0 to an iterator and check for 0 ?
"Is it safe to assign 0 to an iterator and check for 0 ?" No.
You can't assign 0 to an iterator, you have to use some other special value, like end()
.
You should implement next
as shown below, and should also provide has_next()
to check whether there is next item in the list or not.
Itr next()
{
if ( !has_next() )
_lastPostition = _internalList.begin();
return ++_lastPostition;
}
bool has_next() const
{
Itr temp = lastPostition;
return (++temp== _internalList.end());
}
Note: the behaviour of next()
is circular; that is, on reaching end, it returns begin again!
精彩评论