10

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?

Casey
  • 10,297
  • 11
  • 59
  • 88
  • Overloaded operators of `++,--, +,-` – Steephen Sep 17 '15 at 01:28
  • I don't think there is an "iterable" concept, so it is pretty much up to you. There is a [Container](http://en.cppreference.com/w/cpp/concept/Container) concept, and a few iterator ones too. – juanchopanza Sep 17 '15 at 01:50

1 Answers1

15

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).

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 3
    "and the return type of the functions supports the pre-increment operator" Iterator should also have defined typedefs such as `value_type` etc, otherwise using them with standard containers may not compile. The best way to do that would be to subclass `std::iterator`. – Adrian17 Sep 17 '15 at 08:06
  • 6
    Apparently `std::iterator` is deprecated in C++17. – Spidey Apr 11 '19 at 20:51
  • 1
    @Spidey, thanks for pointing that out. Do you know whether there is something else that has replaced `std::iterator` in C++17? – R Sahu Apr 11 '19 at 21:03
  • @RSahu I'm in the process of trying to find a proper solution :) – Spidey Apr 11 '19 at 21:08
  • 2
    @RSahu According to https://www.fluentcpp.com/2018/05/08/std-iterator-deprecated/ `std::iterator` is just a struct defining 5 basic types that the iterator should provide. These 5 basic types aren't complicated and `std::iterator` can be replaced with 5 typedefs/using aliases. As far as I can tell the rest stays the same. – Spidey Apr 11 '19 at 21:50