c++ - std::transform 和 std::plus 如何协同工作?

标签 c++ c++11 c++14

我在阅读 C++ 引用资料时遇到了带有示例的 std::plus 函数。这非常简单,它只是添加了 lhs 和 rhs。代码是:

#include <functional>
#include <iostream>

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

输出: Hello World

我改成了

#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 和 bar 相加。但是它是如何传递给 std::plus 函数的呢?

最佳答案

std::plus<> functor ,这只是实现 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_opstd::plus<>的名字.自 std::plus<>是一个仿函数,C++ 会将对它的“调用”解释为对 operator() 的调用功能,为我们提供所需的行为。

关于c++ - std::transform 和 std::plus 如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568541/

相关文章:

c++ - 在 vector 中存储 boost_shared 指针 - 它很昂贵吗

c++ - 成员变量在另一个线程中没有改变?

c++ - 在 GPU 上计算平方欧氏距离矩阵

c++ - 可变参数模板整数序列的偏移量

c++ - 获取模板中的函数返回类型

c++ - T::* 在模板参数中是什么意思?

c++ - 我可以使用 std::initializer_list 而不是大括号括起来的初始化程序来初始化数组吗?

c++ - shared_ptr 的别名构造函数是干什么用的?

c++ - 段错误(核心转储)错误未解决

c++ - 模板类之外的内部类方法定义