C++中递归局部函数的实现

在编写leetcode-2476题目中,需要将二叉搜索树中序遍历变为升序数组。想到在Rust中声明一个局部函数非常简单,并且可以有效防止局部变量名污染空间。探索了在C++中实现局部函数的方法。

先贴最终代码

class Solution {
public:
    vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
        vector<vector<int>> res;
        vector<int> inOrder = toInOrder(root);
        for (int query : queries) {
            int pos = lower_bound(inOrder.begin(), inOrder.end(), query) - inOrder.begin();
            int lower = -1, upper = -1;
            if (pos >= inOrder.size()) {
                lower = inOrder.back();
                res.push_back({lower, upper});
                continue;
            }

            if (inOrder[pos] == query) {
                lower = query;
                upper = query;
            } else {
                lower = pos-1 >= 0 ? inOrder[pos-1] : -1;
                upper = inOrder[pos];
            }
            res.push_back({lower, upper});
        }
        return res;
    }
private:
    vector<int> toInOrder(TreeNode* root) {
        vector<int> res;

        // helper
        std::function<void(TreeNode*)> inOrder = [&res, &inOrder](TreeNode* root) {
            if (root == nullptr) {
                return;
            }
            inOrder(root->left);
            res.push_back(root->val);
            inOrder(root->right);
        };

        inOrder(root);
        return res;
    }
};

递归局部函数的实现

    vector<int> toInOrder(TreeNode* root) {
        vector<int> res;

        // helper
        std::function<void(TreeNode*)> inOrder = [&res, &inOrder](TreeNode* root) {
            if (root == nullptr) {
                return;
            }
            inOrder(root->left);
            res.push_back(root->val);
            inOrder(root->right);
        };

        inOrder(root);
        return res;
    }
  1. 常见的lambda函数中,会使用auto自动推断函数类型,但是当函数需要调用自身时,必须先显式声明其类型。
#include <functional> // 包含 functional 文件
...
// std::function<{Return-Value}(parameters)
// 采用上述格式声明inOrder为接受一个TreeNode*作为参数,返回void函数的函数 
std::function<void(TreeNode*> inOrder = ...

按上述修改后的函数为

1 std::function<void(TreeNode*)> inOrder = [&res](TreeNode* root) {
2     if (root == nullptr) {
3         return;
4     }
5     inOrder(root->left);
6     res.push_back(root->val);
7     inOrder(root->right);
8 };

第5行和第7行的inOrder提示an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list
2. 将inOrder函数添加到capture list中,可以运行

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值