如何让我自己的惰性迭代器? [英] How could I make my own lazy iterator?
问题描述
我正在做一个C ++ 11类,产生大量的数据。该数据目前来自数据库,它不能完全适合内存。我想为用户提供一个迭代器,它的行为就像普通的STL迭代器,但这将是懒惰的。更准确地说,我可以做这样的事情:
I'm making a C++11 class that produces a huge amount of data. That data currently comes from a database and it cannot fit entirely in memory. I would like to provide the user with an iterator that behaves like regular STL iterators, but that would be lazy. More precisely, I would be able to do something like that :
for (auto& item : big_bunch_of_data) {
do_stuff_with(item);
}
仅在每次迭代时从数据库检索项目。如果我是对的,这个新的语法是糖
With item being retrieved from the database only at each iteration. If I'm right, this new syntax is sugar for
for (stuff::iterator it = big_bunch_of_data.begin();it != big_bunch_of_data.end();it++) {
do_stuff_with(*it);
}
这是否意味着提供 begin
, end
和 operator ++
,我可以有期望的行为?而且,这些方法应该做什么?
Does it mean that by providing begin
, end
and operator++
, I could have the desired behavior ? And, what are these methods supposed to do ? I mean, can I make them lazy without breaking stuff ?
推荐答案
几乎;如果找不到 begin
或 end
对容器类的方法;这是基于范围的for循环在数组上的工作,没有 begin
和 end
成员。它还将通过ADL寻找自由函数 begin
和 end
,最终还会查找 std :: begin
和 std :: end
,因此有很多机会来改进基于范围的for循环支持现有容器。第6.5.4节涵盖了细节。
Almost; the compiler will look in a few other places to get the begin and end iterators if it can't find begin
or end
methods on the container class; this is how range-based for loops work on arrays, that don't have begin
and end
members. It will also look for free functions begin
and end
by ADL, and eventually std::begin
and std::end
, so there's plenty of opportunity to retrofit range-based for loop support to existing containers. Section 6.5.4 covers the details.
对于你的其他问题,迭代器绝对可以是惰性的!一个好的例子是 std :: istream_iterator
,它从控制台读取输入时为延迟。
For your other question, iterators absolutely can be lazy! A good example is std::istream_iterator
which has to be lazy as it reads input from the console.
在中为
循环使用迭代器的要求是它应该满足输入迭代器类别,第24.2.3节;该类别所需的操作为!=
,一元 *
,前后增量 ++
。
The requirement to use an iterator in a for
loop is that it should satisfy the input iterator category, which is described in section 24.2.3; the required operations for that category are !=
, unary *
, and pre- and post-increment ++
.
为了让语言知道你创建了一个输入迭代器,你应该继承 std :: iterator< std :: input_iterator_tag,T,void,T *,T&>
其中 T
(第24.4.3节)。
To let the language know that you've created an input iterator, you should inherit from std::iterator<std::input_iterator_tag, T, void, T *, T &>
where T
is the type your iterator deals in (section 24.4.3).
这篇关于如何让我自己的惰性迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!