std::transform 和 std::p lus 如何协同工作
How std::transform and std::plus work together?
我正在阅读C++参考资料,并遇到了带有示例的std::p lus函数。这很简单,它只是添加了 lhs 和 rhs。代码是:
#include <functional>
#include <iostream>
int main()
{
std::string a = "Hello ";
const char* b = "world";
std::cout << std::plus<>{}(a, b) << 'n';
}
输出:你好世界
我把它改成了
#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 和酒吧加起来。但是它是如何传递给std::p lus函数的呢?
>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()
函数的调用,从而为我们提供所需的行为。
std::p lus STL 提供的一组函子之一。 如果你熟悉函数式编程,它们对函数组合是一种方便。 std::p lus 具体是一个二元运算符,所以它需要两个参数。 std::Transform 将从两个向量发送元素。 您还可以使用 std::bind 将二进制运算符转换为一个参数运算符,基本上将常量绑定到第二个参数。
我个人认为std::p lus及其类似的东西在c ++ 11 lambda函数出现之前更有用。 Lambda 允许您定义一组要对数据执行的操作,而无需处理绑定或 std::p lus 及其同类。
相关文章:
- 我不明白参数和参数如何协同工作
- Qt C++括号匹配和突出显示当前线路功能无法协同工作
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- Emrun 和无头铬 - 如何让这两者协同工作?
- boost::make_shared 失败,但 std::make_shared 工作
- 如何编译Freetype(2)和Harfbuzz(带有Visual studio)使它们协同工作?
- 两个超载的STD ::前进工作如何
- 模板类实例化如何与类继承协同工作
- 如何将RegisterDragDrop,RoInitialize组合在一个线程中协同工作
- 如何让助推upgrade_to_unique_lock+condition_variable协同工作
- Fruchterman-Reingold的吸引力是如何与Boost图库协同工作的
- 如何使Ws2_32.lib与针对Windows 8.1的VS 2013项目协同工作
- 如何在C++中使一个void函数与另一个void功能协同工作
- 插入[n X n]矩阵类型的数据,并在运行时对其进行访问.将std::映射工作
- std::transform 和 std::p lus 如何协同工作
- 右值模板参数隐式用作左值,并且 std::转发工作
- 无法让 cgal 和 hdf5 协同工作
- std::ref 和交换功能似乎不能很好地协同工作
- 类的详细信息:设计一组协同工作的类时出错
- 如何使这两个模板类协同工作?(C++中的属性)