Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c++
Subject: Re: Why can't I understand what coroutines are?
Date: Fri, 09 Aug 2019 19:49:57 -0700
Organization: A noiseless patient Spider
Lines: 37
Message-ID: <86tvap91ka.fsf@mailhub.linuxsc.com>
References: <0qqdkep3adsd1m07tp0gnsn21pkvds12kk@4ax.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="4bad90a7c43721789c432acb03dbc8ee"; logging-data="29048"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19wE16cFpLau9veJ/kEBA5EAdnhjiysBFo="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:/lgRFghV/D63d93Wkw7aFimFCJI= sha1:ckW7Tbj5S1Vh16MSCI5d9KArx3k=
Xref: csiph.com comp.lang.c++:67509
"Alf P. Steinbach" writes:
>> [...]
>
> Anyway, to avoid [a recursive coroutine] I'd probably do
> something like this:
>
>
> auto bftraverse( Node* root )
> -> optional
> {
> stack nodes;
> nodes.push( root );
> while( not nodes.empty() ) {
> const auto p = nodes.top();
> nodes.pop();
> if( p == nullptr ) {
> co_return {};
> }
> co_yield p->data;
> if( p->right ) { nodes.push( p->right ); }
> if( p>left ) { nodes.push( p->left ); }
> }
> }
The function body can be simplified thus:
stack nodes;
nodes.push( root );
while( not nodes.empty() ) {
const auto p = nodes.top();
nodes.pop();
if( !p ) continue;
co_yield p->data;
nodes.push( p->right );
nodes.push( p->left );
}