我必须实现哪些函数才能使类可迭代? [英] What functions must I implement to make a class iterable?
问题描述
我正在编写一个包含同一个类的子对象的集合的类,并且希望使用标准提供的函数来迭代和索引,而不是像以下那样的函数: first()
, next()
, previous()
, last( )
, getchild(x)
等。
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.
在c ++ 14中,在所有情况下,我必须实现函数来使类可迭代/可索引吗?
In c++14, which functions must I implement to make a class iterable/indexable in all cases?
函数:
-
begin()
-
cbegin()
-
rbegin()
-
crbegin()
-
end()
-
cend()
-
rend()
-
我想到了crend()
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()
size()
empty()
还有其他吗?我必须实现的函数,比如预递增/递减或后递增/递减和数组下标运算符,或者它只是 begin()
和 end()
及其变体?
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?
推荐答案
如果您的容器实现 begin()
和 end()
作为成员函数,并且函数的返回类型支持预增量运算符,可以使用它在大多数情况下。我能想到的重要事项是:
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
。您可以使用:
Container c;
for ( auto& item : c ) { ... }
函数与迭代器一起使用。示例:
Functions that work with iterators. Example:
Container c;
Item item;
std::find(c.begin(), c.end(), item);
使迭代器成为<的子类a href =http://en.cppreference.com/w/cpp/iterator/iterator =nofollow> std :: iterator
是确保它与所有标准算法兼容的最佳方法。 (谢谢@Adrian)。
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).
这篇关于我必须实现哪些函数才能使类可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!