Equivalent C++ to Python generator pattern

前端 未结 12 2360
Happy的楠姐
Happy的楠姐 2020-11-28 18:42

I\'ve got some example Python code that I need to mimic in C++. I do not require any specific solution (such as co-routine based yield solutions, although they would be acce

12条回答
  •  再見小時候
    2020-11-28 19:17

    This answer works in C (and hence i think works in c++ too)

    #include 
    
    const uint64_t MAX = 1ll<<32;
    
    typedef struct {
        uint64_t i, j;
    } Pair;
    
    Pair* generate_pairs()
    {
        static uint64_t i = 0;
        static uint64_t j = 0;
        
        Pair p = {i,j};
        if(j++ < MAX)
        {
            return &p;
        }
            else if(++i < MAX)
        {
            p.i++;
            p.j = 0;
            j = 0;
            return &p;
        }
        else
        {
            return NULL;
        }
    }
    
    int main()
    {
        while(1)
        {
            Pair *p = generate_pairs();
            if(p != NULL)
            {
                //printf("%d,%d\n",p->i,p->j);
            }
            else
            {
                //printf("end");
                break;
            }
        }
        return 0;
    }
    

    This is simple, non object-oriented way to mimic a generator. This worked as expected for me.

提交回复
热议问题