【发布时间】:2023-03-08 21:42:01
【问题描述】:
我正在升级到 C++ 11,并且对 https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019 中提到的 lambda 表达式有基本的了解
我对从http://project-thrill.org/捕获的以下代码有以下疑问
以下程序计算文本中每个唯一单词的出现次数
void WordCount(thrill::Context& ctx, std::string input, std::string output)
{
using Pair = std::pair<std::string, size_t>;
auto word_pairs = ReadLines(ctx, input)
.template FlatMap<Pair>(
// flatmap lambda: split and emit each word
[](const std::string& line, auto emit)
{
Split(line, ’ ’, [&](std::string_view sv)
{
emit(Pair(sv.to_string(), 1));
});
});
word_pairs.ReduceByKey(
// key extractor: the word string
[](const Pair& p) { return p.first; },
// commutative reduction: add counters
[](const Pair& a, const Pair& b)
{
return Pair(a.first, a.second + b.second);
})
.Map([](const Pair& p)
{
return p.first + ": " + std::to_string(p.second);
}).WriteLines(output);
}
第一个问题
.template FlatMap是什么
FlatMap 是一个模板类型的 lambda 函数,它在返回 ReadLines 时运行?
在
FlatMap<Pair>内部,值是如何传递给(const std::string& line, auto emit)的,谁传递了值?
在
ReduceByKey函数内部,对于lambda函数的参数[](const Pair& p),值是如何被传递的?
【问题讨论】:
-
您的第一个问题在这里得到解答:stackoverflow.com/questions/610245/…
-
FlatMap 不是 lambda,它需要一个函数作为参数,并且该参数是一个 lambda,它将被包装为一个函数。