Search code examples
c++stliteratoroperator-overloadingrandom-access

How to implement "less than operator" for random access iterator?


I'm implementing custom random access stl iterator. Wrapper for ATL-Classes like CArray. So I have index instead of pointer. My end()-Iterator has index -1.

As i see here compare operators like "less than" must be implemented.

My question is; what should be the result, if one of the compare argument is an end()-Iterator? Is it defined behavior?

VS2015 implements vector_iterator like this;

bool operator<(const _Myiter& _Right) const
{   // test if this < _Right
    _Compat(_Right);
    return (_Ptr < _Right._Ptr);
}

But i'm not sure what will be happend, if _Right or *this is an end()-Iterator.

Edit: The idea that end() has the index as -1 was bad. Now i'm using container size as index for end()-iterator.


Solution

  • Michael Burr's comments are essentially the correct answer.

    operator<(LeftIter,RightIter) should be true if and only if there is a strictly positive number N such that LeftIter+N == RightIter.

    For the element at position P, LeftIter would be container.begin()+P, so there indeed is such a number N. It's container.size()-P, which is indeed always bigger than 0.

    How you implement this is up to you, the Standard just describes the visible behavior.