What functions must I implement to make a class it

2019-01-20 16:08发布

问题:

This question already has an answer here:

  • How to allow range-for loop on my class? [duplicate] 3 answers

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?

回答1:

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