Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
Yola Avatar asked Dec 16 '15 07:12

Yola


1 Answers

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.

like image 181
Angew is no longer proud of SO Avatar answered Oct 20 '22 00:10

Angew is no longer proud of SO