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

≡放荡痞女 提交于 2019-12-19 09:51:14

问题


I was reading C++ reference and came across std::plus function with an example. Which is pretty straight forward, its simply adds lhs and rhs. The code was:

#include <functional>
#include <iostream>

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

output: Hello world

I changed it to

#include <functional>
#include <iostream>

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

output : 6

Now I made

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

I called:

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

and it gave 21 41 61 81 101 which I understand it is adding up both foo and bar. But how it was passed to std::plus function?


回答1:


std::plus<> is a functor, which is just fancy talk for a class that implements operator(). Here's an example:

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

The std::transform you have there is roughly equivalent to:

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;
}

Here, binary_op is the name given to std::plus<>. Since std::plus<> is a functor, C++ will interpret the "call" to it as a call to the operator() function, giving us our desired behavior.




回答2:


std::plus one of a set of functors provided by the STL. If your familiar with functional programming, they are a convenience for function composition. std::plus specifically is a binary operator, so it takes two arguments. std::Transform will send it elements from the two vectors. You can also use std::bind to turn binary operators into one argument operators, basically binding a constant to the second argument.

Personally I think std::plus and its like were more useful before the advent of c++11 lambda functions. Lambda's allow you to define a set of operations to perform on your data without having to deal with binds or std::plus and its ilk.



来源:https://stackoverflow.com/questions/35568541/how-stdtransform-and-stdplus-work-together

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!