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() 作为成员函数,以及返回类型的函数支持预增量运算符,您可以在大多数情况下使用它.我能想到的重要的是:
范围.您可以使用:容器 c;for (auto& item : c) { ... }使用迭代器的函数.示例:
容器 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:
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).
这篇关于我必须实现哪些功能才能使类可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我必须实现哪些功能才能使类可迭代?
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
