c++ - 值在常量表达式 C++ 中不可用

标签 c++

下面的代码在C++中遇到了value is not usable in a constant expression错误


int sumNumbers(TreeNode* root) {

    stack<pair<TreeNode*, int>> st;
    st.push(make_pair(root, root->val));
    int sum = 0;

    while(!st.empty()){
        pair<TreeNode*, int> temp = st.top();
        st.pop();
        TreeNode* node = temp.first;
        int value = temp.second;

        if(node->left==NULL && node->right==NULL){
            sum += value;
        }

        if(node->left){
            st.push(pair< node->left, value*10 + node->left->val >);
        }

        if(node->right){
            st.push(pair< node->right, value*10 + node->right->val >);
        }
    }

    return sum;
}

错误在行中:

if(node->left){
            st.push(pair< node->left, value*10 + node->left->val >);
        }

错误是:

Line 29: Char 37: error: the value of 'node' is not usable in a constant expression st.push(pair< node->left, value*10 + node->left->val >);


我无法弄清楚为什么会在此处遇到此错误?

最佳答案

您想使用make_pair 来创建一个对象,自动设置模板类型:

st.push(make_pair(node->left, value*10 + node->left->val));

右边也一样。

关于c++ - 值在常量表达式 C++ 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54488756/

相关文章:

c++ - 了解 Windows API 中消息处理的不同策略

c++ - Xcode 4.2 无法识别 C++ 原始字符串文字?

c++ - 指向类数据成员 "::*"的指针

c++ - 传递一个成员函数作为 C++ 标准库算法的比较运算符

c++ - 离散事件模拟在 windows 和 linux 中生成不同的结果

c++ - c++ : error: must use '.*' or '->*' to call pointer-to-member function in function 中的函数指针

c++ - 取消引用从线程返回的指针导致;段错误 : 11

c++ - 我应该在一个函数被调用的次数非常多的情况下使用它吗?

c++ - 我如何从 cpp 中的任何给定数字的右边获得第三位数字?

指针的 C++ 运算符重载