| A possible use of for-each to solve this problem. | Lecture 5 - slide 37 : 39 Program 1 |
// Example from C++ in a Nutshell, page 337-338. Slightly revised.
#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){
if (first_time)
first_time = false;
else if (item < prev_item)
sorted = false;
prev_item = item;
}
operator bool(){return sorted;}
};
int main(){
using namespace std;
list<int> lst;
lst.push_back(3); lst.push_back(15); lst.push_back(9); lst.push_back(11);
lst.push_back(13); lst.push_back(15); lst.push_back(19); lst.push_back(21);
if(for_each(lst.begin(), lst.end(), Is_sorted<int>()))
cout << "The list lst is sorted" << endl;
else
cout << "The list lst is NOT sorted" << endl;
}