One day STL forum a friend asked about the use of bind2st, began to think very simple:
void print(int& a,const int b)
{
a+=b;
}
int main()
{
list<int> my_list;
.........
for_each(my_list.begin(),my_list.end(), bind2nd(print,3) );
}
The goal is to loop, each node plus 3
To bind the second value of a function to 3 by bind2nd
But no, it's wrong.
If we want to achieve the goal, how should we change it??
Later a debugging, found not so easy. Can you find out where the problem is?
After looking at the help document to resolve, look at my reply:
For_each is the need to use functor, bind2st objects are also functor rather than functions.
If you need to use bind2st, then you need to inherit from Binary_function.
For_each will not let you modify the elements, so your request is not achieved.
There are instructions in the STL Programming Manual:
For_each "Unaryfunction does not apply any non-constant operation through its argument"
If you want to meet the requirements, you can use transform.
The following code is an example:
struct printx: public binary_function<int, int, int>
{
int operator()(int a, int b)const
{
cout<<a+b<<endl;
return a+b;
}
};
int main()
{
vector<int> my;
my.push_back(0);
my.push_back(1);
my.push_back(2);
copy(my.begin(), my.end(), ostream_iterator<int>(cout, " "));
cout<<"\n-----"<<endl;
for_each(my.begin(),my.end(), bind2nd(printx() , 3) );
cout<<"\n-----"<<endl;
copy(my.begin(), my.end(), ostream_iterator<int>(cout, " "));
cout<<"\n-----"<<endl;
transform(my.begin(),my.end(),my.begin(), bind2nd(printx() , 3) );
cout<<"\n-----"<<endl;
copy(my.begin(), my.end(), ostream_iterator<int>(cout, " "));
return 0;
}
It seems not so easy, STL at the beginning of use, it is not so easy, its programming idea is very good, but if not accustomed to this style, very easy to have problems, plus compile error message is not friendly, it is difficult to correct errors. Therefore, it is recommended that beginners try not to use some troublesome operation. Use the container's own function more than once, step-by-step.