SimpleHeap.h

00001 /*  _________________________________________________________________________
00002  *
00003  *  UTILIB: A utility library for developing portable C++ codes.
00004  *  Copyright (c) 2001, Sandia National Laboratories.
00005  *  This software is distributed under the GNU Lesser General Public License.
00006  *  For more information, see the README file in the top UTILIB directory.
00007  *  _________________________________________________________________________
00008  */
00009 
00010 // 
00011 // SimpleHeap.h
00012 //
00041 #ifndef __SimpleHeap_h
00042 #define __SimpleHeap_h
00043 
00044 #ifdef __GNUC__
00045 #pragma interface
00046 #endif
00047 
00048 #include "_generic.h"
00049 #include "AbstractHeap.h"
00050 #include "compare.h"
00051 
00052 template <class T>
00053 class SimpleHeap;
00054 
00055 
00061 template <class T>
00062 class SimpleHeapItem 
00063 {
00064   friend class AbstractHeap<SimpleHeapItem<T>,T>;
00065   friend class SimpleHeap<T>;
00066 
00067 public:
00068 
00070   void write(ostream& os) {os << Key;}
00072   T& key() {return Key;}
00074   int compare(const T& key)
00075                 {return ::compare(Key,key);}
00076 
00077 private:
00078 
00080   T Key;
00082   int element;
00084   int ctr;
00085 
00087   SimpleHeapItem(const T* Key_) : Key(*Key_), element(0), ctr(1) {}
00088 };
00089 
00090 
00091 
00092 template <class T>
00093 class SimpleHeap : public AbstractHeap<SimpleHeapItem<T>,T>
00094 {
00095 public:
00096 
00098   SimpleHeap(const char* nameBuff = "Unnamed")
00099         : AbstractHeap<SimpleHeapItem<T>,T>(nameBuff), 
00100                 duplicate_flag(true), check_duplicates_flag(false) {}
00101 
00103   bool& duplicate() {return duplicate_flag;}
00105   bool& check_duplicates() {return check_duplicates_flag;}
00106 
00107 protected:
00108  
00110   bool duplicate_flag;
00112   bool check_duplicates_flag;
00113 
00115   SimpleHeapItem<T>* insert(T* key);
00117   void extract(SimpleHeapItem<T>* item, bool& status);
00118 
00119 };
00120 
00121 
00122 template <class T>
00123 SimpleHeapItem<T>* SimpleHeap<T>::insert(T* key)
00124 {
00125 duplicate_flag = false;
00126 if (check_duplicates_flag) {
00127    SimpleHeapItem<T>* item = find(*key);  
00128    if (item) {
00129       item->ctr++;
00130       duplicate_flag = true;
00131       return item;
00132       }
00133    }
00134 return AbstractHeap<SimpleHeapItem<T>,T>::insert(key);
00135 }
00136 
00137 
00138 template <class T>
00139 void SimpleHeap<T>::extract(SimpleHeapItem<T>* item, bool& status)
00140 {
00141 if (check_duplicates_flag) {
00142    SimpleHeapItem<T>* item = find(item->key());
00143    if (item) {
00144       item->ctr--;
00145       if (item->ctr > 0) {
00146          status=true;
00147          return;
00148          }
00149       }
00150    }
00151 AbstractHeap<SimpleHeapItem<T>,T>::extract(item,status);
00152 }
00153 
00154 #endif