Hi,

In below code snippet , can anyone let me know how to print the functor value output (3,4,5,6,7) without
embedding add function in class.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void add ( int i)
{
i=i+2;

}

int main()
{
vector <int> vec ={1,2,3,4,5};

for_each(vec.begin(), vec.end(),add);


for (auto i:vec)
{

cout<<i;
}


return 1;
}

Could you elaborate on your question?

you need to pass reference instead of value . Give a try it will work

void add ( int &i)
{
i=i+2;

}

I'm pretty sure the standard says something about modifying the value past to the function in for_each(). If you want to change a value past to a function then I would investigate the transform() function.

Oops. My bad, I was thinking about something else. Please ignore.

This is done simply with the for_each loop plus lammbda.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


int main()
{
vector <int> vec ={1,2,3,4,5};

for_each(vec.begin(), vec.end(),[](int &c){ cout << c+2 <<endl;});

return 1;
}
## out put
3
4
5
6
7

Happy? ))

Is there any particular reason you're using for_each when you already have C++11's range based for loops available? Is it part of an assignment that your add() function has to exist? The following would be easier.

for(auto& i : vec)
    i += 2;

for(auto i : vec)
    cout << i;

Thanks for your apply. why cant we use below expression with for loop.
even it works with for_eac.

for(string i:vecs,add)
{
cout<<i;

}

Because that's not the syntax for range-based for loop. I can't imagine it would work with for_each either because you're iterating through strings, and your add() functions operates on and int.

The for_each and lambda is clearly superior in the solution of this task. plain and simple ))

The for_each and lambda is clearly superior in the solution of this task. plain and simple ))

Why? for doesn't even require you to write a function.

Why? for doesn't even require you to write a function.

Because it is robust, compact , no error prone, easy to read and efficient.
Thats according to the task before us currently.
Understood?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.