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).
这篇关于我必须实现哪些功能才能使类可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我必须实现哪些功能才能使类可迭代?


基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01