std :: transform和std :: plus如何协同工作? [英] How std::transform and std::plus work together?
问题描述
我正在阅读C ++参考,并通过示例遇到了std :: plus函数。这很简单,只需添加lhs和rhs。代码是:
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';
}
输出:Hello world
output: 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函数?
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?
推荐答案
std :: plus<>
是functor ,对于实现 operator()的类来说,这只是花哨的话题code>。例如:
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; }
};
std :: transform
,您大致相当于:
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;
}
此处, binary_op
是 std :: plus<>
的名称。由于 std :: plus<>
是函子,因此C ++会将对它的调用解释为对 operator()的调用
函数,给我们我们想要的行为。
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.
这篇关于std :: transform和std :: plus如何协同工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!