How to check if a simple C ++ library iterator can be extended?

Suppose I have a class that encapsulates a std container:

class Stash { list<int> Data; public: list<int>::const_iterator GetAccess() const { return Data.begin(); } }; 

This is a very convenient way to get the user to read data in the form of an iterator. However, I cannot find another way to compare the iterator with container.end() . So, I would like to know if it is possible to do this only using stdlib, or should I write an iterator class myself (for example, using the can_advance method).

This may be a relevant question, but it asks if the iterator is valid, and if it can move forward. I could not find any information about the latter.

+4
source share
3 answers

You cannot do this; one iterator does not contain information when it is at the end of the sequence that it points to.

This is usually achieved by providing a range (think std::make_pair(cont.begin(), cont.end()) ) or by providing the begin() and end() methods for your class, effectively making it a range.

+4
source

Iterators work in pairs: an iterator that indicates the start of a sequence and an iterator that indicates the end of a sequence. Therefore, all containers have member functions begin() and end() , so you can see the sequence of values ​​that the container controls.

It would be much more idiomatic to change the name of GetAccess to begin and add end . With end() , you can also apply standard algorithms to data.

+2
source

What you seem to be asking for is a lookahead iterator. You can write a class to β€œadapt” the iterator to a view where the adapter just stays one step ahead of your code:

 template<class FwdIter> class lookahead_iterator { public: lookahead_iterator(const FwdIter& begin): cur_iter(begin), next_iter(++begin) {} operator FwdIter() const { return cur_iter; } lookahead_iterator<FwdIter>& operator ++() { cur_iter = next_iter++; return *this; } // Other methods as needed. private: FwdIter cur_iter; FwdIter next_iter; }; 

Needless to say, this gets a lot harder if you need more than a forward iterator.

0
source

All Articles