简体   繁体   English

使用bind1st还是bind2nd?

[英]Use bind1st or bind2nd?

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. 我知道bind1st和bind2nd之间的用法差异,方法一和方法二都为我提供了预期的结果。

Is it true that there is no big difference in this case (ie usage of transform) so that I can use either bind1st or bind2nd? 在这种情况下(即转换的使用)没有大的区别,这样我可以使用bind1st或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和bind2nd是否相同。

bind1st binds the first parameter of plus<int>() functor, and bind2nd binds the second parameter. bind1st绑定plus<int>() bind1st的第一个参数, bind2nd绑定第二个参数。 In case of plus<int> , it doesn't make any difference, as 10+20 and 20+10 are same. plus<int>情况下,它没有任何区别,因为10+2020+10是相同的。

But if you do that with minus<int> , it would make difference, as 10-20 and 20-10 aren't same. 但是如果你用minus<int>做到这一点,那就会有所不同,因为10-2020-10不一样。 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 演示: http//ideone.com/IfSdt

bind1st binds the first parameter of a function while bind2nd binds the second parameter. bind1st绑定函数的第一个参数,而bind2nd绑定第二个参数。 Since the two parameter types are the same in this case and operator+ is symmetrical it makes no difference. 由于在这种情况下两个参数类型相同而且operator+是对称的,因此没有区别。

在这种情况下,它们分别转换为5 + a和a + 5,它们被编译为完全相同。

For your particular case 对于你的特殊情况

bind1st()

and

bind2nd()

are same . 一样的

Thus is because, plus() binary function operator looks like below 因此, plus()二元函数运算符如下所示

plus(arg1, arg2)

So, when you use bind1st(plus<int>(), 5) the call to plus would look as under 因此,当您使用bind1st(plus<int>(), 5) ,对plus的调用将显示为

plus(5, vwInts)

so, above will add every element of vector with a value 5 所以,上面将添加值为5的vector的每个元素

And when you use bind2nd(plus<int>(), 5) the call to plus would look as under 当你使用bind2nd(plus<int>(), 5) ,对plus的调用看起来就像

plus(vwInts, 5)

so, above will add every element of vector with a value 5 . 所以,上面将添加值为5的vector的每个元素。

Hence both are same in your case 因此在你的情况下两者都是一样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM