Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use bind1st or bind2nd?

Tags:

c++

stl

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.

like image 216
q0987 Avatar asked Jul 28 '11 18:07

q0987


3 Answers

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

like image 171
Nawaz Avatar answered Nov 08 '22 01:11

Nawaz


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.

like image 22
Mark B Avatar answered Nov 08 '22 01:11

Mark B


In this case, they'd translate respectively to 5 + a and a + 5, which gets compiled to exactly the same.

like image 3
Andrea Bergia Avatar answered Nov 08 '22 00:11

Andrea Bergia