// Demonstrating use of for_each and reverse algorithms with list #include #include #include void show_int (int x) { cout << x << " "; } void show_int_square (int x) { cout << x*x << " "; } int main() { cout << "Demonstrating use of for_each algorithm:" << endl; list list2; // populating the list using "push_back" list2.push_back(39); list2.push_back(99); list2.push_back(79); list2.push_back(69); list2.push_back(59); list2.push_back(89); list2.push_back(89); list2.push_back(49); // long way to list the squares of each number in list2 // this one uses iterators... cout << "LONG WAY FOR SQUARES: " << endl; list::iterator ip; for (ip=list2.begin(); ip!=list2.end(); ip++) cout << (*ip) * (*ip) << " " ; cout << endl; // easy way is to use "for_each" algorithm with a function cout << "SHORT WAY FOR SQUARES: " << endl; for_each(list2.begin(), list2.end(), show_int_square); cout << endl; // show the base list cout << "BEFORE REVERSE: " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; // reverse the list by using "reverse" algorithm reverse(list2.begin(), list2.end()); cout << "AFTER REVERSE: " << endl; for_each(list2.begin(), list2.end(), show_int); cout << endl; }