我在阅读 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_op
是std::plus<>
的名字.自 std::plus<>
是一个仿函数,C++ 会将对它的“调用”解释为对 operator()
的调用功能,为我们提供所需的行为。
关于c++ - std::transform 和 std::plus 如何协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568541/