// Example from C++ in a Nutshell (2003), page 337-338. Slightly revised. Rather tricky. #include #include #include // An object of an instance of Is_sorted is used as a function // with state, corresponding to the three data members. template class Is_sorted{ private: bool first_time, // true when applied first time sorted; // true as along as prefix is sorted T prev_item; // the previous item public: Is_sorted(): first_time{true}, sorted{true}{ } void operator() (const T& item){ // Called for each item in the list. if (first_time) // If two elements out of order is met, sorted becomes false. first_time = false; else if (item < prev_item) // two elements out of order. sorted = false; prev_item = item; } operator bool(){return sorted;} }; int main(){ using namespace std; // Make a list with some elements: list lst{3, 15, 9, 11, 13, 15, 21}; // Make an instance of the class IsSorted: Is_sorted is_sorted{}; // Use for_each to find out if lst is sorted: if(for_each(lst.begin(), lst.end(), is_sorted)) // for_each returns the object is_sorted cout << "The list lst is sorted" << endl; // via the boolean conversion operator. else cout << "The list lst is NOT sorted" << endl; // The given list is not sorted. }