Equivalent C++ to Python generator pattern

前端 未结 12 2349
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:13

    Just as a function simulates the concept of a stack, generators simulate the concept of a queue. The rest is semantics.

    As a side note, you can always simulate a queue with a stack by using a stack of operations instead of data. What that practically means is that you can implement a queue-like behavior by returning a pair, the second value of which either has the next function to be called or indicates that we are out of values. But this is more general than what yield vs return does. It allows to simulate a queue of any values rather than homogeneous values that you expect from a generator, but without keeping a full internal queue.

    More specifically, since C++ does not have a natural abstraction for a queue, you need to use constructs which implement a queue internally. So the answer which gave the example with iterators is a decent implementation of the concept.

    What this practically means is that you can implement something with bare-bones queue functionality if you just want something quick and then consume queue's values just as you would consume values yielded from a generator.

提交回复
热议问题