/* Lecture code 10.0 * * Demonstrating the boost::lambda library along with BOOST_FOREACH on an array of numbers. * Note that this code will only work if you have the Boost libraries installed on your system. */ #include #include #include #include #include // For BOOST_FOREACH #include // For _1, _2. using namespace std; using namespace boost::lambda; /* This next line simplifies the use of BOOST_FOREACH by letting us just * write foreach instead. */ #define foreach BOOST_FOREACH const int NUM_INTS = 24; int main() { /* Seed the randomizer. Consult a reference for more info. */ srand((unsigned int)time(NULL)); int myArray[NUM_INTS]; /* Use generate to populate the array with random numbers. */ generate(myArray, myArray + NUM_INTS, rand); /* Sort the numbers in reverse order. The final parameter is a lambda expression * which returns true if the first integer is greater than the second. */ sort(myArray, myArray + NUM_INTS, _2 < _1); /* Transform the numbers by replacing each with its square, minus 137. */ transform(myArray, myArray + NUM_INTS, myArray, (_1 * _1) - 137); /* Print out the array using foreach. */ foreach(int n, myArray) cout << n << endl; return 0; }