home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C19 / Sorted.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  61 lines

  1. //: C19:Sorted.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Template specialization
  7. #ifndef SORTED_H
  8. #define SORTED_H
  9. #include <vector>
  10.  
  11. template<class T>
  12. class Sorted : public std::vector<T> {
  13. public:
  14.   void sort();
  15. };
  16.  
  17. template<class T>
  18. void Sorted<T>::sort() { // A bubble sort
  19.   for(int i = size(); i > 0; i--)
  20.     for(int j = 1; j < i; j++)
  21.       if(at(j-1) > at(j)) {
  22.         // Swap the two elements:
  23.         T t = at(j-1);
  24.         at(j-1) = at(j);
  25.         at(j) = t;
  26.       }
  27. }
  28.  
  29. // Partial specialization for pointers:
  30. template<class T>
  31. class Sorted<T*> : public std::vector<T*> {
  32. public:
  33.   void sort();
  34. };
  35.  
  36. template<class T>
  37. void Sorted<T*>::sort() {
  38.   for(int i = size(); i > 0; i--)
  39.     for(int j = 1; j < i; j++)
  40.       if(*at(j-1) > *at(j)) {
  41.         // Swap the two elements:
  42.         T* t = at(j-1);
  43.         at(j-1) = at(j);
  44.         at(j) = t;
  45.       }
  46. }
  47.  
  48. // Full specialization for char*:
  49. template<>
  50. void Sorted<char*>::sort() {
  51.   for(int i = size(); i > 0; i--)
  52.     for(int j = 1; j < i; j++)
  53.       if(strcmp(at(j-1), at(j)) > 0) {
  54.         // Swap the two elements:
  55.         char* t = at(j-1);
  56.         at(j-1) = at(j);
  57.         at(j) = t;
  58.       }
  59. }
  60. #endif // SORTED_H ///:~
  61.