繁体   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

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

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

因为,到目前为止我看到的所有例子总是使用方法二。 我想知道在上面的例子中bind1st和bind2nd是否相同。

bind1st绑定plus<int>() bind1st的第一个参数, bind2nd绑定第二个参数。 plus<int>情况下,它没有任何区别,因为10+2020+10是相同的。

但是如果你用minus<int>做到这一点,那就会有所不同,因为10-2020-10不一样。 试试吧。

插图:

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;
}

输出:

 30
 30
-10
 10

演示: http//ideone.com/IfSdt

bind1st绑定函数的第一个参数,而bind2nd绑定第二个参数。 由于在这种情况下两个参数类型相同而且operator+是对称的,因此没有区别。

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

对于你的特殊情况

bind1st()

bind2nd()

一样的

因此, plus()二元函数运算符如下所示

plus(arg1, arg2)

因此,当您使用bind1st(plus<int>(), 5) ,对plus的调用将显示为

plus(5, vwInts)

所以,上面将添加值为5的vector的每个元素

当你使用bind2nd(plus<int>(), 5) ,对plus的调用看起来就像

plus(vwInts, 5)

所以,上面将添加值为5的vector的每个元素。

因此在你的情况下两者都是一样的

暂无
暂无

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

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