即使a被证明是假的,"while( bool a && bool b )"也会检查a和b吗?

Will "while( bool a && bool b )" check both a and b even if a proves to be false?

在某些情况下,我必须遍历 array/vector 来寻找满足涉及该元素的 value.In 过去的条件的元素,我会选择一个简单的 forif 语句一起循环,但最近我看到一段代码似乎更 simple.To 更精确:

我以前是这样做的:

for( int i = 0; i < vector.size(); i++ )
    if( condition[i] )
       do_stuff;

现在我对这个很好奇:

int i = 0;
while( i < vector.size() || condition[i] )
    i++;

我喜欢这个定义,它更短,事实上我相信它更容易阅读,但令我困扰的是向量为空的情况。

我不确定 || 处理布尔值的方式,它是否检查第一个条件,如果为假则检查第二个条件?还是它仍然检查两者?如果是这样,应该会出现错误,因为我正在检查不存在的元素的条件。

在它编译的空向量上尝试代码后 运行 很好,只是为了确保我也尝试了这个:

bool a , b = false;
if( b || a )
   dostuff;

而且效果也很好。

但对我来说,检查不存在的值的条件似乎仍然不完全正确,我不确定我是否应该使用 it.Is 它好还是我应该去别的地方?

任何帮助都会很棒。

编辑 0:它仍然应该抛出错误,因为向量是空的。 0 < 0 returns false ,所以仍然会检查第二个条件。

是,operator|| 执行短路评估。

Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands

这意味着对于 while( i < vector.size() || condition[i] ),如果 i < vector.size()true 那么 condition[i] 将不会被评估;如果它是 false 那么 condition[i] 将被进一步评估;现在你可能会看到这里有错误。