How to return a pointer as an iterator?

I need to implement iterators, and I don't have time to create cool iterator classes, so I decided to just return the pointers. This is something like this.

int* begin() { return p; } 

But I want them to behave like regular 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?

+6
source share
2 answers

Pointers do satisfy the requirements of the iterator (a pointer satisfies even the most specialized requirements of a random access iterator). Your problem is that when implementing the standard library that you use, the iterators provided, for example, std::vector supports more operations than the iterator requires.

In other words, the standard does not guarantee that ++vi.begin() will work for std::vector iterator vi . It happens that you are working on your standard library implementation, but that’s implementation detail. An iterator that would not support this is still a perfectly valid iterator.

So, to answer your question: if you want to quickly create a reserve for an iterator that will support all iterator operations, you can certainly use a pointer. If you need fast iterator support that will additionally support all the operations supported by the standard library implementation, in addition to the iterator requirements, you may have to deploy your own class.

+9
source

The minimal iterator is pretty easy to crack using boost :

 #include <boost/iterator/iterator_facade.hpp> using namespace boost; struct Int100 { int arr[100]; struct iterator : iterator_facade<iterator,int,forward_traversal_tag> { iterator( int* p = nullptr ) : p(p) {} void increment() { ++p; } bool equal(const iterator& other) const { return p == other.p; } int& dereference() const { return *p; } int* p; }; iterator begin() { return {arr}; } iterator end() { return {arr+100}; } }; 

This supports the syntax *++begin() you are looking for.

0
source

All Articles