std :: transform和std :: plus如何一起工作?

mlh*_*zan 3 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';
}
Run Code Online (Sandbox Code Playgroud)

输出:Hello world

我改成了

#include <functional>
#include <iostream>

int main()
{
   int a = 5;
   int b = 1;
   std::cout << std::plus<int>{}(a, b) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出:6

现在我做了

foo vector = 10 20 30 40 50
bar vector = 11 21 31 41 51
Run Code Online (Sandbox Code Playgroud)

我打了电话:

std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());
Run Code Online (Sandbox Code Playgroud)

并且它给出了21 41 61 81 101,据我所知它将foo和bar加起来.但它如何传递给std :: plus函数?

Bri*_*uez 9

std::plus<>是一个函子,对于一个实现的类来说,这只是一种奇特的讨论operator().这是一个例子:

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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