码迷,mamicode.com
首页 > 编程语言 > 详细

用C语言实现yield

时间:2017-07-22 14:26:53      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:out   ++   cci   tin   yield   div   state   gen   int   

用C语言实现yield


C/C++中没有yield语法,有的时候想用产生器,自己实现一个循环会感觉很麻烦。C/C++应该如何实现产生器呢?

class FibonacciGenerator {
public:
  FibonacciGenerator() : a(0), b(0), state(0) {}
  int generate() {
    switch (state) {
      case 0:
        for (a = 0, b = 1; ; c = a + b) {
          state = 1;
          return c;
      case 1:;
        }
    }
  }
private:
  int a, b, c;
  int state;
}

这个代码真的很神奇,我也没搞懂他是如何运行的,但是循环式的generator似乎可以这么写。

参考

用C语言实现yield

标签:out   ++   cci   tin   yield   div   state   gen   int   

原文地址:http://www.cnblogs.com/stevendes1/p/7221106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!