3

私のコードは

TreeNode *sortedArrayToBST(vector<int> &num) {
    function<TreeNode*(int,int)> func=
        [&func,&num](int s, int e){
            TreeNode* p = NULL;
            if(s>e) return NULL; // change to return p would compile
            int m = (s+e)/2;
            p = new TreeNode(num[m]);
            p->left = func(s,m-1);
            p->right = func(m+1,e);
            return p;
        };
    return func(0,num.size()-1);
}

Solutions.cpp:957:21: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
Solutions.cpp:959:29: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:959:29: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]
Solutions.cpp:962:12: error: inconsistent types ‘TreeNode*’ and ‘int’ deduced for lambda return type
Solutions.cpp:962:12: error: invalid conversion from ‘TreeNode*’ to ‘int’ [-fpermissive]

TreeNode* 型の NULL を作成してコードを修正しました。私の質問は、NULL ポインターを返すためだけに一時変数を宣言する必要がないように、型で NULL を作成する方法です。NULL(TreeNode); のようなもの。

4

2 に答える 2

6

使用する:

function<TreeNode*(int,int)> func=
    [&func,&num](int s, int e) -> TreeNode* /*explicitly define return type*/ {
        //nullptr is beter than NULL with C++11
        TreeNode* p = nullptr;
        if(s>e) return nullptr; // we return nullptr here
        int m = (s+e)/2;
        p = new TreeNode(num[m]);
        p->left = func(s,m-1);
        p->right = func(m+1,e);
        return p;
    };

http://www.stroustrup.com/C++11FAQ.html#nullptr (nullptr に関する情報) を参照してください。

コンパイラ エラーが発生する理由

NULL は実際には整数であり、これにより、コンパイラがラムダの戻り値の型を決定しようとするときに混乱が生じます (return NULL を記述すると整数が返され、後で行の下に return p (TreeNode*) もあります)コンパイラは、ラムダの戻り値の型 (int か TreeNode へのポインタか) を推測する必要がある型を認識していませんか?

戻り値の型を明示的に指定して nullptr を使用することで、あいまいさを解消できます (C++11 でこれを行う必要があるためです)。

于 2013-09-25T19:48:11.737 に答える
2

これは c++11 です。nullptr を使用する必要があります。NULL は基本的に廃止されています。また、null には型がなく、(通常は) 0 です。NULL は基本的に単なる int (0) であるため、コード エラーです。このゲームnullptrでは、型があるため、戻り値も機能しない可能性がありnullptr_tます。

編集:私はチェックしましたが、残念ながら私の最初の考えは正しかったので、型をnullptr持っているnullptr_tので、戻り値の型を明示的に指定できます。で[...](...)->TreeNode*{...}、すべてがうまくいくはずです

于 2013-09-25T19:46:26.383 に答える