Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What functions must I implement to make a class iterable? [duplicate]

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?

like image 403
Casey Avatar asked Sep 17 '15 01:09

Casey


People also ask

How do I make a class iterable in python?

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.

What does it mean that a Python class is Iterable?

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.


1 Answers

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:

  1. range-for. You can use:

    Container c;
    for ( auto& item : c ) { ... }
    
  2. 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).

like image 190
R Sahu Avatar answered Nov 05 '22 14:11

R Sahu