【问题标题】:The use of std::bind with a binary operation function in C++在 C++ 中将 std::bind 与二进制操作函数一起使用
【发布时间】:2013-05-20 19:55:15
【问题描述】:

我正在尝试了解 std::bind 的工作原理。我写了以下内容:

#include <iostream>
#include <algorithm>
#include <functional>


using namespace std::placeholders;

int fun2(int i,int j)
{
   return i+j;
}


int fun(int i)
{
  return i;
}

int main()
{
 std::vector<int> v9={1,2,3,4,5,6,6,7};
 std::transform(v9.begin(),v9.end(),v9.begin(),[](int i){return i;}); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),fun); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun,_1)); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun2,_1,_2)); //does not work
}

std::transform 也接受二进制操作函数。所以我尝试编写 fun2 并使用 std::bind (主要的最后一行),但它不起作用。谁能给我举个例子 std::bind 如何使用占位符(2,3 或更多)?

【问题讨论】:

  • std::transform 只传递一个参数。你的意思是像std::bind(fun2, _1, 5)这样的事情吗?
  • 当它通过两个时除外:(2) :)
  • 如果你不绑定任何参数,那么使用std::bind 真的没有意义。
  • @jrok,我的生活已经永远改变了。谢谢!
  • @sftrabbit 你是对的,但这不是一个真正的程序,我只是想了解 std::bind 的工作原理。

标签: c++ stl stdbind


【解决方案1】:

采用二元仿函数的std::transform 的重载需要四个迭代器,而不是三个,因为它在两个输入范围上运行,而不是一个。例如:

#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>

int fun2(int i,int j)
{
   return i+j;
}

int main()
{
  using namespace std::placeholders;
  std::vector<int> v1={1,2,3,4,5,6,6,7};
  std::vector<int> v2;
  std::transform(v1.begin(), v1.end(), v1.begin(), 
                 std::back_inserter(v2), std::bind(fun2,_1,_2));
  for (const auto& i : v2)
    std::cout << i << " ";
  std::cout << std::endl;
}

当然,在现实生活中你不会在这里使用std::bind

【讨论】:

  • 你是对的,我的错。 std::transform(v9.begin(),v9.end(),v9.begin(),v9.end(),std::bind(fun2,_1,_2));
  • @AvraamMavridis:您确定该代码给您同样的错误吗?什么是完整的错误? (如果是 Visual Studio,则完全错误出现在“输出”窗口中,而不是“错误”窗口中)
  • @MooingDuck 代码(在评论中)没有给出任何错误,它可以编译。
  • @AvraamMavridis 对,它可以编译,但会在运行时失败。
  • @AvraamMavridis 我添加了一个工作示例(它与您的不完全相同,但您明白了)。
猜你喜欢
  • 2012-10-28
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 2016-10-04
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多