std::transform 和 std::p lus 如何协同工作

How std::transform and std::plus work together?

本文关键字:std 协同工作 transform lus      更新时间:2023-10-16

我正在阅读C++参考资料,并遇到了带有示例的std::p lus函数。这很简单,它只是添加了 lhs 和 rhs。代码是:

#include <functional>
#include <iostream>
int main()
{
   std::string a = "Hello ";
   const char* b = "world";
   std::cout << std::plus<>{}(a, b) << 'n';
}

输出:你好世界

我把它改成了

#include <functional>
#include <iostream>
int main()
{
   int a = 5;
   int b = 1;
   std::cout << std::plus<int>{}(a, b) << 'n';
}

输出 : 6

现在我做了

foo vector = 10 20 30 40 50
bar vector = 11 21 31 41 51

我打电话给:

std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());

给出了 21 41 61 81 101,我知道它把 foo 和酒吧加起来。但是它是如何传递给std::p lus函数的呢?

>std::plus<>是一个函子,对于实现operator()的类来说,这只是花哨的谈话。 下面是一个示例:

struct plus {
    template <typename A, typename B>
    auto operator()(const A& a, const B& b) const { return a + b; }
};

您在那里拥有的std::transform大致相当于:

template<typename InputIt1, typename InputIt2, 
         typename OutputIt, typename BinaryOperation>
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, 
                   OutputIt d_first, BinaryOperation binary_op)
{
    while (first1 != last1) {
        *d_first++ = binary_op(*first1++, *first2++);
    }
    return d_first;
}

在这里,binary_op是给std::plus<>起的名字。 由于std::plus<>是一个函子,C++会将对它的"调用"解释为对operator()函数的调用,从而为我们提供所需的行为。

std::p lus STL 提供的一组函子之一。 如果你熟悉函数式编程,它们对函数组合是一种方便。 std::p lus 具体是一个二元运算符,所以它需要两个参数。 std::Transform 将从两个向量发送元素。 您还可以使用 std::bind 将二进制运算符转换为一个参数运算符,基本上将常量绑定到第二个参数。

我个人认为std::p lus及其类似的东西在c ++ 11 lambda函数出现之前更有用。 Lambda 允许您定义一组要对数据执行的操作,而无需处理绑定或 std::p lus 及其同类。