Search code examples
c++functionreturn-valuelvalue

How to return a pointer as an iterator?


I need to implement iterators, and i don't have time to make nice iterator classes, so i have decided to just return pointers. It is something like this

int* begin()
{
    return p;
}

But i want them to behave as usual stl iterators

*++begin(); // doesn't work because returned pointer isn't l-value

std::vector<int> vi{ 0, 1 };
*++vi.begin(); // works fine

int* p = begin();
*++p;  // works fine as well

How can i do this?


Solution

  • Pointers do meet the iterator requirements prefectly (a pointer meets even the most-specialised Random access iterator requirements). Your problem comes from the fact that in the implementation of the standard library which you're using, the iterators provided by e.g. std::vector support more operations than the iterator requirements require.

    In other words, the standard does not guarantee that ++vi.begin() will work for a std::vector iterator vi. It happens to work on your implementation of the standard library, but it's an implementation detail. An iterator which would not support that is still a perfectly valid iterator.

    So, to answer your question: if you want a quick stand-in for an iterator which will support all iterator operations, you can certainly use a pointer. If you want a quick stand-in for an iterator which will additionally support all the operations your standard library implementation supports in addition to iterator requirements, you might have to roll out your own class.