问题
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