简体   繁体   中英

logical or expression c++

I have a problem using the Logical OR operator in C++. The problem is coming that the right-side expression is not evaluated if the left-side is true. I have two deque-s and I need to popLeft from them with a while, but if I can pop from the first deque, I don't pop from the second because is not evaluated, by the OR operator. How can I overcome this problem. Here is the piece of code:

while( D.popLeft( k ) || E.popLeft( m ) )
{
    if( k < m )
    {
      C.pushRight( k );
      E.pushLeft( m );
    }
    else
    {
      C.pushRight( m );
      D.pushLeft( k );
    }
}

I imagine you only want to run the content of the loop when you can fill both m and k, right? Then simply replace your OR with an AND:

while( D.popLeft( k ) && E.popLeft( m ) )
{
    if( k < m )
    {
      C.pushRight( k );
      E.pushLeft( m );
    }
    else
    {
      C.pushRight( m );
      D.pushLeft( k );
    }
}

Then both pops will be executed.

Assuming you want to keep your || (and not use a && ), you can evaluate separatly:

bool canPopE = E.popLeft( m );
bool canPopD = D.popLeft( k );
bool canPop = canPopD || canPopE;

while( canPop )
{
    if( k < m )
    {
      C.pushRight( k );
      E.pushLeft( m );
    }
    else
    {
      C.pushRight( m );
      D.pushLeft( k );
    }

    canPopE = E.popLeft( m );
    canPopD = D.popLeft( k );
    canPop = canPopD || canPopE;
}

使用&&运算符

while( D.popLeft( k ) && E.popLeft( m ) )

By default C++ logical operators use short circuit mechanism, if you want to do your loop without short circuit, use eager operator "|" instead. This will evaluate both expressions any way. http://en.wikipedia.org/wiki/Short-circuit_evaluation

while( D.popLeft( k ) | E.popLeft( m ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM