Use bind1st or bind2nd?

Use bind1st or bind2nd?

本文关键字:bind2nd or bind1st Use      更新时间:2023-10-16
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,这是真的吗?

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

bind1st绑定plus<int>()函子的第一个参数,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

Demo: http://ideone.com/IfSdt

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

在这种情况下,它们将分别翻译为5 + a和a + 5,它们被编译为完全相同的

对于您的特殊情况

bind1st()

bind2nd()
同样是

这是因为,plus()二进制函数运算符看起来像下面的

plus(arg1, arg2)

所以,当你使用bind1st(plus<int>(), 5)时,对+的调用看起来就像在

下面
plus(5, vwInts)

因此,上面将添加vector的每个值为5

的元素

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

下面
plus(vwInts, 5)

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

因此在你的例子中是相同的