c++的function用法
偶然看别人的题解了解到的(std::function是从C++11开始支持的特性)
在学function用法之前可以先了解一下C语言的函数指针,然后这里面还有类模板template、lambda表达式和重载方面的知识
function<void(TreeNode*)> DFS = [&] (TreeNode* root) {};
function<int(int,int)> DFS = [&] (int u, int p) {};
- 不难发现黄色高亮部分和粉色高亮部分的对应关系,紫色高亮部分则是函数的返回值类型
- 等式右边是lambda表达式
直接上题吧,从题中掌握它的用法
1.力扣2476 二叉搜索树最近节点查询
2476. 二叉搜索树最近节点查询 - 力扣(Leetcode)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) { 15 vector<vector<int>> res; 16 vector<int> v; 17 function<void(TreeNode*)> DFS = [&] (TreeNode* root) { 18 if (root == nullptr) 19 return; 20 v.push_back(root -> val); 21 DFS(root -> left); 22 DFS(root -> right); 23 }; 24 DFS(root); 25 sort(v.begin(),v.end()); 26 for (auto x : queries) { 27 int a = -1,b = -1; 28 auto it = lower_bound(v.begin(),v.end(),x); 29 if (it != v.end()) { 30 b = *it; 31 if (b == x) a = b; 32 else if (it != v.begin()) a = *prev(it); 33 }else 34 a = *prev(it); 35 res.push_back({a,b}); 36 } 37 return res; 38 } 39 };
2.力扣2477 到达首都的最少油耗
2477. 到达首都的最少油耗 - 力扣(Leetcode)
1 class Solution { 2 public: 3 long long minimumFuelCost(vector<vector<int>>& roads, int seats) { 4 long long ans = 0; 5 int n = roads.size() + 1; 6 vector<vector<int> > G(n); 7 for (auto x : roads) { 8 G[x[0]].push_back(x[1]); 9 G[x[1]].push_back(x[0]); 10 } 11 12 function<int(int,int)> DFS = [&] (int u, int p){ 13 int res = 1; 14 for (auto v : G[u]) { 15 if (v != p) { 16 int x = DFS(v,u); 17 ans += (x + seats - 1) / seats; 18 res += x; 19 } 20 } 21 return res; 22 }; 23 DFS(0,-1); 24 return ans; 25 } 26 };
3.力扣46 全排列
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 int n = nums.size(); 5 vector<bool> visited(22, false); 6 vector<vector<int> > res; 7 vector<int> ans; 8 function<void(int,int)> dfs = [&] (int tar, int cnt){ 9 if (cnt == n - 1){ 10 ans.push_back(tar); 11 res.push_back(ans); 12 ans.pop_back(); 13 return; 14 } 15 ans.push_back(tar); 16 visited[tar + 11] = true; 17 for (auto x : nums) { 18 if (visited[x + 11] == false) 19 dfs (x, cnt + 1); 20 } 21 ans.pop_back(); 22 visited[tar + 11] = false; 23 }; 24 for (auto x : nums) { 25 dfs (x,0); 26 } 27 return res; 28 } 29 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现