如何在C ++中实现一个生成器? [英] How can I implement a generator in C++?

查看:93
本文介绍了如何在C ++中实现一个生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在C ++中实现一个生成器,如Python。
Python可以使用关键字yield这样做。
但是如何在C ++中做呢?

I want to know how to implement a generator , like Python, in C++? Python can use keyword "yield" to do so. But how to do it in C++?

推荐答案

在C ++中我们有'iterators'。一个明确要求一个interator,显式增加和解引用它。

In C++ we have 'iterators'. One explicitly asks for an interator, explicitly increments it and dereferences it.

如果你想让它们与标准库函数一起使用,它们应该主要从 std :: forward_iterator ,并实现一些函数。

If you want them to be used with the standard library functions, they should mostly be derived from std::forward_iterator, and implement a number of it's functions.

另一种方法来模拟一个集合允许一个函数作为一个成员函数的参数,将该函数的所有值馈送(产生)给该函数:

An other way to mimic kindof a generator on a collection is allowing a function as argument to a member function that feeds (yields) all of it's values to that function:

struct MyCollection {
    int values[30];

    template< typename F >  
    void generate( F& yield_function ) const {
       int* end = values+30; // make this better in your own code :)
       for( auto i: values ) yield_function( *i );
    }
};

// usage:
c.generate([](int i){ std::cout << i << std::endl; });

// or pre-C++11:
struct MyFunction { 
    void operator() (int i)const { printf( "%d\n", i); }
};
MyCollection c;
c.generate( MyFunction() );

这篇关于如何在C ++中实现一个生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆