如何用 C++ 实现生成器?

问题描述 投票:0回答:5

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

c++ generator idioms
5个回答
12
投票

在 C++ 中,我们有“迭代器”。明确要求一个迭代器,明确增加它并取消引用它。

如果你希望它们与标准库函数一起使用,它们应该大多源自

std::forward_iterator
,并实现它的一些功能。

模仿集合上的生成器的另一种方法是允许一个函数作为成员函数的参数,该成员函数将其所有值提供给(产生)该函数:

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: use a function object
struct MyFunction { 
    void operator() (int i)const { printf( "%d\n", i); }
};
MyCollection c;
c.generate( MyFunction() );

7
投票

详细说明迭代器的实现:这是一个例子。它可以用作循环变量,或在 std 算法中。

#include <iterator>

template< typename T, typename TDiff = T >
struct TGenerator : public std::iterator<std::forward_iterator_tag,T,TDiff> {
  T from,to;
  T value;
  TDiff step;
  bool issentinel;

  TGenerator( T from, T to, TDiff step, bool sentinel = false )
    : from(from),to(to),step(step),issentinel(sentinel), value(from)
  {}

  void operator++(){ value += step; }

  const T& operator*()const { return value; }

  bool operator!=( const TGenerator& other ) const {
    return value<to;
  }

  TGenerator sentinel()const { return TGenerator(0,0,0,true); }

};


#include <algorithm>
#include <iostream>

int main()
{
  TGenerator<int> i(0,10,3);
  std::copy( i, i.sentinel(), std::ostream_iterator<int>( std::cout, " " ) );

    return 0;
}

6
投票

你确实做不到,但你可以假装做到。这是一种可以在 C 中伪造它的方法,您也可以在 C++ 中使用它。


3
投票

多次调用协程并获得不同的答案意味着您可以保持某种状态。保持状态的方法是对象。让它们看起来像函数调用的方法是运算符重载。有关一些示例,请参阅维基百科中的函数对象文章。


1
投票

你可以使用boost.context(抱歉,还没有在boost发行版上,你必须从boostVault获取它)。

典型的示例代码如下:

#include <iostream>
#include <boost/context.hpp>

using namespace std;

struct Parameters {
  int par1;
  float par2;
};

boost::context c1;
boost::context c2;

void F(void* parameters) {
  Parameters& pars = *(Parameters*)parameters;
  cout << pars.par1 << endl;
  c2.jump_to(c1);
  cout << pars.par2 << endl;
};

int main() {
  c1 = boost::context::current();
  Parameters p;
  p.par1 = 8;
  c2 = boost::context::create_context( F , c1 , p );
  c1.jump_to(c2);
  p.par2 = 1.3;
  c1.jump_to(c2);
}
© www.soinside.com 2019 - 2024. All rights reserved.