我正在阅读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<>
是一个函子,对于一个实现的类来说只是花哨的演讲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()
函数的调用,从而为我们提供了所需的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句