for_each and normal function
if we use the for_each function with one list and one normal function then for each element the function will be called.
Then what is the advantage of using function object with for_each.
Code:
#include<iostream>
#include<algorithm>
#include<list>
using namespace std;
void addElem(int &elem)
{
elem +=10;
}
class AddValue
{
private:
//the value to add
int theValue;
public:
//constructor initializes the value to add
AddValue(int val) : theValue(val) {}
//the function call for the element adds the value
void operator() (int& elem) const
{
elem += theValue;
}
};
int main()
{
list<int>lst1;
int cnt=1;
for(;cnt<11;)
{
lst1.push_back(cnt++);
}
list<int>::const_iterator itr = lst1.begin();
for_each(lst1.begin(),lst1.end(),addElem);
for(;itr != lst1.end();++itr)
{
cout<< *itr << " ";
}
for_each(lst1.begin(),lst1.end(),addElem);
itr=lst1.begin();
cout<<endl;
for(;itr != lst1.end();++itr)
{
cout<< *itr << " ";
}
cout<<endl<<"------------------"<<endl;
for_each(lst1.begin(), lst1.end(),AddValue(10));
itr=lst1.begin();
for(;itr != lst1.end();++itr)
{
cout<< *itr << " ";
}
for_each(lst1.begin(), lst1.end(),AddValue(10));
itr=lst1.begin();
cout<<endl;
for(;itr != lst1.end();++itr)
{
cout<< *itr << " ";
}
cout<<endl;
return 0;
}
If i see the above code the calling a normal function and calling a function object is giving same flexibility and output.
Then why what is the real advantage of using function object here.
Re: for_each and normal function
Quote:
Originally Posted by Rajesh1978
If i see the above code the calling a normal function and calling a function object is giving same flexibility and output.
Then why what is the real advantage of using function object here.
Change the code to perform adding by 20 instead of 10. You are not allowed to modify addElem or the AddValue class, or to create a new function or class.
Re: for_each and normal function
I can just say Brilliant.
Thanks in one line u explained it very well