BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #102609同步于 2023/4/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

LeetCode题解中的lambda表达式

TCZY
2023/4/19镜像同步3 回复
力扣第49. 字母异位词分组,这个题目的官方题解用到了hashmap函数,重写了hash函数,重写过程中用了lambda表达式,没太能看懂,源代码如下 ```cpp class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { // 自定义对 array<int, 26> 类型的哈希函数 auto arrayHash = [fn = hash<int>{}] (const array<int, 26>& arr) -> size_t { return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) { return (acc << 1) ^ fn(num); }); }; unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp(0, arrayHash); for (string& str: strs) { array<int, 26> counts{}; int length = str.length(); for (int i = 0; i < length; ++i) { counts[str[i] - 'a'] ++; } mp[counts].emplace_back(str); } vector<vector<string>> ans; for (auto it = mp.begin(); it != mp.end(); ++it) { ans.emplace_back(it->second); } return ans; } }; ``` 其中的fn,以及在accumulate累加函数中似乎又定义了一个lambda?看着很迷惑,不清楚如何下手,还是说这就不是lambda表达式?请大佬解惑@nuanyangyang
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
midareru机器人#1 · 2023/4/19
fn=hash<int>{}是捕捉列表里的初始化,个人理解是相当于一个static变量。 accumulate能传lambda作为累加时的操作方法。 不能很确定是不是的,lz可以查查lambda的捕捉域,以及accumulate的用法。
TCZY机器人#2 · 2023/4/19
谢谢,我现在大概知道是accumulate又接受了一个lambda表达式,但还不理解为什么fn在捕捉列表里,但却没有定义,以及fn(num)的作用 【 在 midareru 的大作中提到: 】 : fn=hash<int>{}是捕捉列表里的初始化,个人理解是相当于一个static变量。 : accumulate能传lambda作为累加时的操作方法。 : 不能很确定是不是的,lz可以查查lambda的捕捉域,以及accumulate的用法。 : ............
Vampire机器人#3 · 2023/4/19
先聲明,我不懂 c++ > 为什么fn在捕捉列表里 目測是 by-copy capture with an initializer,參考 https://en.cppreference.com/w/cpp/language/lambda > fn(num)的作用 hash 每個字母的計數以便匯總成整個 array 的 hash