algorithms/for-each-examples-f15/for-each-1.cpp - A possible use of for-each to solve this problem. | Lecture 6 - slide 23 : 40 Program 1 |
// Example from C++ in a Nutshell (2003), page 337-338. Slightly revised. Rather tricky. #include <iostream> #include <algorithm> #include <list> // An object of an instance of Is_sorted is used as a function // with state, corresponding to the three data members. template<typename T> 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<int> lst{3, 15, 9, 11, 13, 15, 21}; // Make an instance of the class IsSorted: Is_sorted<int> 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. }