我必须实现哪些功能才能使类可迭代?

What functions must I implement to make a class iterable?(我必须实现哪些功能才能使类可迭代?)
本文介绍了我必须实现哪些功能才能使类可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包含同一类的子对象集合的类,并希望使用标准提供的函数而不是以下函数来迭代和索引它们:first()next()previous()last()getchild(x) 等p>

在 c++14 中,我必须实现哪些函数才能使类在所有情况下都可迭代/可索引?

功能:

  • begin()
  • cbegin()
  • rbegin()
  • crbegin()
  • end()
  • cend()
  • rend()
  • cred()

想到,虽然,可能不一定所有都需要实现.也可选(为方便程序员):

  • size()
  • empty()

是否还有其他必须实现的函数,例如前自增/自减或后自增/自减和数组下标运算符,或者它真的只是 begin()end() 及其变体?

解决方案

如果你的容器实现了 begin()end() 作为成员函数,以及返回类型的函数支持预增量运算符,您可以在大多数情况下使用它.我能想到的重要的是:

  1. 范围.您可以使用:

    容器 c;for (auto& item : c) { ... }

  2. 使用迭代器的函数.示例:

    容器 c;项目项目;std::find(c.begin(), c.end(), item);

使迭代器成为 std::iterator 是确保它与所有标准算法兼容的最佳方式.(感谢@Adrian).

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?

解决方案

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

这篇关于我必须实现哪些功能才能使类可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)