I am writing a class that contains a collection of child objects of the same class and would like to iterate, and index, through them using the standard-provided functions instead of functions like: first()
, next()
, previous()
, last()
, getchild(x)
etc.
In c++14, which functions must I implement to make a class iterable/indexable in all cases?
The functions:
begin()
cbegin()
rbegin()
crbegin()
end()
cend()
rend()
crend()
come to mind, although, probably not necessarily all of them need be implemented. Also optionally (for programmer convenience):
size()
empty()
Are there any other functions that I must implement, like the pre-increment/decrement or post-increment/decrement and array subscript operators, or is it really just begin()
and end()
and their variants?
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.
An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. Familiar examples of iterables include lists, tuples, and strings - any such sequence can be iterated over in a for-loop.
If your container implements begin()
and end()
as member functions, and the return type of the functions supports the pre-increment operator, you can use it in most contexts. The important ones that I can think of are:
range-for
. You can use:
Container c;
for ( auto& item : c ) { ... }
Functions that work with iterators. Example:
Container c;
Item item;
std::find(c.begin(), c.end(), item);
Making the iterator a sub-class of std::iterator
is best way to ensure that it will be compatible with all the standard algorithms. (Thanks @Adrian).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With