Equivalent C++ to Python generator pattern

前端 未结 12 2374
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 18:55

    Something like this is very similar:

    struct pair_sequence
    {
        typedef pair result_type;
        static const unsigned int limit = numeric_limits::max()
    
        pair_sequence() : i(0), j(0) {}
    
        result_type operator()()
        {
            result_type r(i, j);
            if(j < limit) j++;
            else if(i < limit)
            {
              j = 0;
              i++;
            }
            else throw out_of_range("end of iteration");
        }
    
        private:
            unsigned int i;
            unsigned int j;
    }
    

    Using the operator() is only a question of what you want to do with this generator, you could also build it as a stream and make sure it adapts to an istream_iterator, for example.

提交回复
热议问题