logical or expression c++

让人想犯罪 __ 提交于 2019-12-12 03:32:02

问题


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 );
    }
}

回答1:


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.




回答2:


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;
}



回答3:


use && operator

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



回答4:


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 ) )


来源:https://stackoverflow.com/questions/13668643/logical-or-expression-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!