问题
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.
回答1:
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
回答2:
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.
回答3:
In this case, they'd translate respectively to 5 + a and a + 5, which gets compiled to exactly the same.
回答4:
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
来源:https://stackoverflow.com/questions/6863677/use-bind1st-or-bind2nd