A friend of mine asked how to use the newer for_each and is it similar to the foreach in php, so here is the example that I gave and thus doing it online as well.
To start with the foreach (php version here) does loop over data and so does the for_each in c++, but the main difference is that the for_each in c++ is basically a for loop
for (; first!=last;++first)
functionCall(*first);
where the functionCall is the parameter passed in to do something with that part of the data.
The great thing with c++ is that you are able to use either a method, structure etc as long as it is able to output a variable then we are good.
So here is a example, please note that I am loading up a vector
void printNumber (int i) {
cout << "Print the number from a function : " << i << "\n";
}
for_each(v.begin(), v.end(), printNumber);
here we are using the for_each (where the v is a vector) passing in the start and end of the vector with a function as the last parameter.
and here
// create a object that can use the operator() to output value passed in.
struct structToOutput {
void operator() (int i) {
cout << "Struct to output : " << i << "\n";
}
} structToOutputObject;
for_each(v.begin(), v.end(), structToOutputObject);
will output the values differently but in essence still able to access the values.
Here is the code in full
#include
#include
#include
using namespace std;
void printNumber (int i) {
cout << "Print the number from a function : " << i << "\n";
}
// create a object that can use the operator() to output value passed in.
struct structToOutput {
void operator() (int i) {
cout << "Struct to output : " << i << "\n";
}
} structToOutputObject;
int main(int argc, char* argv[])
{
// lets load up some dummy data.
vector v;
for (int i =0; i< 10; i++)
v.push_back(i);
// run through the vector using a standard function with parameter
for_each(v.begin(), v.end(), printNumber);
// output using a operator() method
for_each(v.begin(), v.end(), structToOutputObject);
return 0;
}
with the output being
Print the number from a function : 0
Print the number from a function : 1
Print the number from a function : 2
Print the number from a function : 3
Print the number from a function : 4
Print the number from a function : 5
Print the number from a function : 6
Print the number from a function : 7
Print the number from a function : 8
Print the number from a function : 9
Struct to output : 0
Struct to output : 1
Struct to output : 2
Struct to output : 3
Struct to output : 4
Struct to output : 5
Struct to output : 6
Struct to output : 7
Struct to output : 8
Struct to output : 9
How to compile with g++
g++ -o -std=c++11