我必须实现哪些功能才能使类可迭代?
我正在编写一个包含同一类的子对象集合的类,并希望使用标准提供的函数而不是以下函数来迭代和索引它们: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).
相关文章