Is there a way to have a return value from the function that I pass to foreach.
For ex:
I have,
void myfunction (int i)
{
cout << " " << i;
}
vector<int> myvector;
myvector.push_back(10);
for_each (myvector.begin(), myvector.end(), myfunction);
Lets say, I want to count the number of elements in the vector using some rule, I want to have a return value from myFunction, is this possible?
No. But you can make
myfunctiona functor, pass it a pointer to some memory, and store your return value through that pointer.Edit: As the comments have pointed out, my first example would’ve failed as
for_eachwould have made a copy ofMyFunctor, so we couldn’t have retrieved the return value from our original object. I’ve fixed along the lines of the original approach; but you really should look at GMan’s solution which is more elegant. I’m not sure about the portability, but it does work on mygcc(4.4.2). And as the others have mentioned, whenever possible, use what<algorithm>provides.