00 /* 01 * for_each.cpp 02 * 03 * Author: Simonas Saltenis / Kurt Nørmark 04 * Example from C++ in a Nutshell (2003), page 337-338. Slightly revised. 05 */ 06 07 #include <iostream> 08 #include <algorithm> 09 #include <list> 10 11 // An object of an instance of Is_sorted is used as a function 12 // with state, corresponding to the two data members. 13 template<typename T> 14 class Is_sorted{ 15 private: 16 bool first_time, // true when applied first time 17 sorted; // true as along as prefix is sorted 18 T prev_item; // the previous item 19 20 public: 21 Is_sorted(): first_time{true}, sorted{true}{ } 22 23 void operator() (const T& item) // Called for each item in the list. 24 { 25 if (first_time) // If two elements out of order is met, sorted becomes false. 26 first_time = false; 27 else if (item < prev_item) // two elements out of order. 28 sorted = false; 29 prev_item = item; 30 } 31 32 operator bool(){ return sorted; } 33 }; 34 35 int main() 36 { 37 using namespace std; 38 39 // Make a list with some elements: 40 list<int> lst{3, 15, 9, 11, 13, 15, 21}; 41 42 // Make an instance of the class IsSorted: 43 Is_sorted<int> is_sorted{}; 44 45 // Use for_each to find out if lst is sorted: 46 if(for_each(lst.begin(), lst.end(), is_sorted)) // for_each returns the object is_sorted 47 cout << "The list lst is sorted" << endl; // via the boolean conversion operator. 48 else 49 cout << "The list lst is NOT sorted" << endl; // The given list is not sorted. 50 } 51 52 53 54