从有条件(或三元)运算符返回

nak*_*mis 2 c++ visual-studio-2010

有人可以告诉我为什么在使用Ternary运算符时无法返回表达式的原因吗?

while( root != nullptr )
{
    if( current->data > v ) {
        ( current->left == nullptr ) ? return false : current = current->left;
    } else if( current->data < v ) {
        current->right == nullptr ? return false : current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;
Run Code Online (Sandbox Code Playgroud)

当我尝试返回false时,为什么会出错?我知道我可以这样做:

return ( ( 0 == 1 ) ? 0 : 1 );
Run Code Online (Sandbox Code Playgroud)

但是当试图从其中一个表达式返回时,编译器的问题是什么?

Ted*_*opp 8

问题是return语句没有定义的值(它不是表达式),而三元运算符的右边两个元素中的每一个都应该有一个值.你的代码中还有一个错误:循环应该current是不是的测试nullptr; root不会通过循环改变,所以循环永远不会正常退出.

只需将其重写为嵌套if语句:

current = root;
while( current != nullptr )
{
    if( current->data > v ) {
        if( current->left == nullptr ) return false;
        current = current->left;
    } else if( current->data < v ) {
        if( current->right == nullptr) return false;
        current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;
Run Code Online (Sandbox Code Playgroud)

实际上,对于这个特定的逻辑,你根本不需要内部return语句:

current = root;
while( current != nullptr )
{
    if( current->data > v ) {
        current = current->left;
    } else if( current->data < v ) {
        current = current->right;
    } else if( current->data == v ) {
        return true;
    }
}
return false;
Run Code Online (Sandbox Code Playgroud)

但是,如果您迷恋三元运算符并且必须使用它,您可以:

current = root;
while( current != nullptr )
{
    if( current->data == v ) {
        return true;
    }
    current = (current->data > v) ? current->left : current->right;
}
return false;
Run Code Online (Sandbox Code Playgroud)