没有在C ++ lambda express中指定可变的,但是我仍然能够修改捕获的变量

时间:2018-11-08 22:10:54

标签: c++ lambda

void postOrder(Node *root) {
    Node* lastPrinted = nullptr;
    stack<Node*> container;
    container.push(root);
    while (!container.empty()) {
        Node* current = container.top();
        function<void()> printer = [&](){
            cout << current->data << " ";
            lastPrinted = current;
            container.pop();
        };
        if (!current->right & !current->left) {
            printer();
            continue; 
        }
        if (current->right) {
            if (current->right==lastPrinted) {
                printer();
                continue; 
            }
            else container.push(current->right);
        }
        if (current->left) {
            if (current->left==lastPrinted) {
                printer();
                continue; 
            }
            else container.push(current->left);
        }
    }
}

上面的代码有效。在lambda函数中,未指定可变打印机。但是在函数中,container和lastPrinted被修改。为什么允许?

这里是Node类,以备您测试:

class Node {
    public:
        int data;
        Node *left;
        Node *right;
        Node(int d) {
            data = d;
            left = NULL;
            right = NULL;
        }
};

0 个答案:

没有答案