使用 bind1st 还是 bind2nd? [英] Use bind1st or bind2nd?

查看:55
本文介绍了使用 bind1st 还是 bind2nd?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

vectorvwInts;向量vwIntsB;for(int i=0; i<10; i++)vwInts.push_back(i);变换(vwInts.begin(),vwInts.end(),插入器(vwIntsB,vwIntsB.begin()),bind1st(plus(), 5));//方法一变换(vwInts.begin(),vwInts.end(),插入器(vwIntsB,vwIntsB.begin()),bind2nd(plus(), 5));//方法二

我知道 bind1st 和 bind2nd 之间的用法差异,并且方法一和方法二都为我提供了预期的结果.

在这种情况下(即转换的使用)真的没有大的区别,所以我可以使用 bind1st 或 bind2nd?

因为,到目前为止,我看到的所有示例都使用方法二.我想知道上述情况下的 bind1st 和 bind2nd 是否相同.

解决方案

bind1st 绑定plus()函子的第一个参数,和bind2nd 绑定第二个参数.在plus的情况下,没有任何区别,因为10+2020+10是相同的.>

但是如果你用 minus 来做,那会有所不同,因为 10-2020-10 不是'一样.尝试这样做.

插图:

int main() {auto p1 = bind1st(plus(),10);auto p2 = bind2nd(plus(),10);cout<<p1(20)<<结束;cout<<p2(20)<<结束;auto m1 = bind1st(minus(),10);auto m2 = bind2nd(minus(),10);cout<<m1(20)<<结束;cout<<m2(20)<<结束;返回0;}

输出:

 3030-1010

演示:http://ideone.com/IfSdt

vector<int> vwInts;
vector<int> vwIntsB;

for(int i=0; i<10; i++)
    vwInts.push_back(i);

transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()),
        bind1st(plus<int>(), 5)); // method one

transform(vwInts.begin(), vwInts.end(), inserter(vwIntsB, vwIntsB.begin()),
        bind2nd(plus<int>(), 5)); // method two

I know the usage difference between bind1st and bind2nd and both method one and method two provide the expected results for me.

Is it true that there is no big difference in this case (i.e. usage of transform) so that I can use either bind1st or bind2nd?

Since, all examples I saw so far always use the method two. I would like to know whether or not bind1st and bind2nd in above case are same.

解决方案

bind1st binds the first parameter of plus<int>() functor, and bind2nd binds the second parameter. In case of plus<int>, it doesn't make any difference, as 10+20 and 20+10 are same.

But if you do that with minus<int>, it would make difference, as 10-20 and 20-10 aren't same. Just try doing that.

Illustration:

int main () {
  auto p1 = bind1st(plus<int>(),10);
  auto p2 = bind2nd(plus<int>(),10);
  cout << p1(20) << endl;
  cout << p2(20) << endl;

  auto m1 = bind1st(minus<int>(),10);
  auto m2 = bind2nd(minus<int>(),10);
  cout << m1(20) << endl;
  cout << m2(20) << endl;
  return 0;
}

Output:

 30
 30
-10
 10

Demo : http://ideone.com/IfSdt

这篇关于使用 bind1st 还是 bind2nd?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆