简体   繁体   中英

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.

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?

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 binds the first parameter of a function while bind2nd binds the second parameter. Since the two parameter types are the same in this case and operator+ is symmetrical it makes no difference.

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

For your particular case

bind1st()

and

bind2nd()

are same .

Thus is because, plus() binary function operator looks like below

plus(arg1, arg2)

So, when you use bind1st(plus<int>(), 5) the call to plus would look as under

plus(5, vwInts)

so, above will add every element of vector with a value 5

And when you use bind2nd(plus<int>(), 5) the call to plus would look as under

plus(vwInts, 5)

so, above will add every element of vector with a value 5 .

Hence both are same in your case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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