C语言中的Python风格迭代器

6 投票
3 回答
895 浏览
提问于 2025-04-15 11:26

在Python中,“yield”语句可以让我们简单地从一个过程(函数)中进行迭代。它的好处是,我们不需要提前计算出所有的值,也不需要把这些值存储在一个大小不固定的数组里。

那么,在C语言中,有没有类似的方式可以用“yield”来进行迭代呢?

3 个回答

0

不。

简单明了!

3

我有时候会开玩笑提到这个网址:C语言中的协程

我认为你问题的正确答案是:没有直接对应的东西,想要模拟出来的效果可能也不会那么简单或者好用。

6

下面是一个社区共享的自我回答,可以被选为“最佳”答案。请将点赞和点踩直接给真正的自我回答。

这是我找到的方法:

    /* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */
#include <stdio.h>

typedef enum{false=0, true=1}bool;

/* the following line is the only time I have ever required "auto" */
#define FOR(i,iterator) auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define     YIELD(x) if(!yield(x))return
#define     BREAK return false
#define     CONTINUE return true
#define OD CONTINUE; }
/* Warning: _Most_ FOR(,){ } loops _must_ have a CONTINUE as the last statement. 
 *  *   Otherwise the lambda will return random value from stack, and may terminate early */

typedef void iterator; /* hint at procedure purpose */
static volatile void *yield_init;
#define YIELDS(type) bool (*yield)(type) = yield_init

iterator fibonacci(int n){
   YIELDS(int);
   int i;
   int pair[2] = {0,1};
   YIELD(0); YIELD(1);
   for(i=2; i<n; i++){
      pair[i%2] = pair[0] + pair[1];
      YIELD(pair[i%2]);
   }
}

iterator factors(int n){
  YIELDS(int); 
  int i;
  for(i=2; i*i<=n; i++){
    while(n%i == 0 ){
      YIELD(i);
      n/=i;
    }
  }
  YIELD(n);
}

main(){
    FOR(int i, fibonacci(32)){
        printf("%d:", i);
        int sum = 0;
        FOR(int factor, factors(i)){
            sum += factor;
            printf(" %d",factor);
            CONTINUE;
        }
        printf(" - sum of factors: %d\n", sum);
        CONTINUE;
    }
}

这个想法来自于 http://rosettacode.org/wiki/Prime_decomposition#ALGOL_68 - 但用C语言写起来更好理解。

撰写回答