【问题标题】:template lambda expression in C++C++ 中的模板 lambda 表达式
【发布时间】: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&lt;Pair&gt; 内部,值是如何传递给(const std::string&amp; line, auto emit) 的,谁传递了值?


ReduceByKey函数内部,对于lambda函数的参数[](const Pair&amp; p),值是如何被传递的?

【问题讨论】:

  • 您的第一个问题在这里得到解答:stackoverflow.com/questions/610245/…
  • FlatMap 不是 lambda,它需要一个函数作为参数,并且该参数是一个 lambda,它将被包装为一个函数。

标签: c++ c++11 lambda


【解决方案1】:

.template FlatMap是什么

在语法上必须指出FlatMap 是模板成员,而&lt; 是显式模板参数的一部分,而不是比较运算符。

FlatMap 是一个模板类型的 lambda 函数,它在返回 ReadLines? 时运行?`

那不是一回事。 FlatMap 是一个模板成员函数,它接收一个 Callable 作为它的唯一参数。这里是用 lambda 表达式调用的。

FlatMap&lt;Pair&gt; 内部,值是如何传递给(const std::string&amp; line, auto emit) 的,谁传递了值?

FlatMap 的正文。就像在 lambda 中如何调用 emit 一样。大概是对输入中的每一行调用一次,并从每个输入行生成多个 Pair 作为输出。

ReduceByKey函数内部,对于lambda函数的参数[](const Pair&amp; p),值是如何被传递的?

同样的方法。 ReduceByKey 有两个Callable 参数,根据word_pairs 的成员调用它们(这是FlatMap 的结果)

它将根据第一个函数对它看到的每个项目进行分类,然后在每个类别中与第二个函数组合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多