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).
这篇关于我必须实现哪些功能才能使类可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我必须实现哪些功能才能使类可迭代?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
