text cover

Data Abstraction and Problem Solving with C++

Walls and Mirrors

by Frank M. Carrano

Addison Wesley Logo

example235.cpp

Go to the documentation of this file.
00001 
00017 #include <list>
00018 #include <iostream>
00019 #include <string>
00020 #include <new>
00021 using namespace std;
00022 
00023 // define a list of pointer strings
00024 typedef list<string*, allocator<string*> > STRING_PTR;
00025 
00026 namespace std
00027 {
00028    // override the default behavior of sort
00029    template<> struct greater<string*>
00030    {
00031       // override operator() to create a function object
00032       bool operator() (string* s1, string *s2)
00033       {
00034     return (*s1) > (*s2);
00035       }  // end operator()
00036    }; // end std::greater
00037 }  // end std namespace
00038 
00039 int main()
00040 {
00041    // create a list of pointer strings and a list iterator
00042    STRING_PTR groceryList;
00043    STRING_PTR::iterator i;
00044 
00045    // create pointers to strings in a random order
00046    // insert the string pointers to the end of the list
00047    try
00048    {
00049       string* str = new string ("apples");
00050       groceryList.insert(groceryList.end(), str);
00051       str = new string ("bread");
00052       groceryList.insert(groceryList.end(), str);
00053       str = new string ("juice");
00054       groceryList.insert(groceryList.end(), str);
00055       str = new string ("carrots");
00056       groceryList.insert(groceryList.end(), str);
00057 
00058       cout << "Number of items on my grocery list: "
00059       << groceryList.size() << endl;
00060 
00061       // sort with the overridden function object
00062       groceryList.sort(greater<string*>());
00063 
00064       // print out the list of strings
00065       cout << "Items after the predicate sort are:" << endl;
00066       i = groceryList.begin();
00067       while (i != groceryList.end())
00068       {  cout << (*(*i)).c_str() << endl;
00069       i++;
00070       }  // end while
00071    }  // end try
00072    catch (bad_alloc e)
00073    {  cout << e.what() << endl;
00074    }  // end catch
00075 }  // end main

Generated on Sun Aug 27 13:05:37 2006 for AWLogo by  doxygen 1.4.6