Teuchos Package Browser (Single Doxygen Collection)  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Teuchos_Hashtable.hpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Teuchos: Common Tools Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
42 #ifndef TEUCHOS_HASHTABLE_H
43 #define TEUCHOS_HASHTABLE_H
44 
49 #include "Teuchos_ConfigDefs.hpp"
50 #include "Teuchos_Array.hpp"
51 #include "Teuchos_HashUtils.hpp"
52 
53 namespace Teuchos
54 {
55  using std::string;
56 
60  template<class Key, class Value> class HashPair
61  {
62  public:
64  inline HashPair() : key_(), value_() {;}
66  inline HashPair(const Key& key, const Value& value)
67  : key_(key), value_(value) {;}
68 
70  Key key_;
72  Value value_;
73  };
74 
80  template<class Key, class Value> class Hashtable
81  {
82  public:
83 
85  inline Hashtable(int capacity=101, double rehashDensity = 0.8);
86 
88  inline bool containsKey(const Key& key) const ;
89 
91  inline const Value& get(const Key& key) const ;
92 
94  inline void put(const Key& key, const Value& value);
95 
97  inline void remove(const Key& key);
98 
100  inline int size() const {return count_;}
101 
103  inline void arrayify(Array<Key>& keys, Array<Value>& values) const ;
104 
106  inline double avgDegeneracy() const {return avgDegeneracy_;}
107 
109  inline double density() const {return ((double)count_)/((double) capacity_);}
110 
112  inline void setRehashDensity(double rehashDensity);
113 
115  inline std::string toString() const ;
116 
117  private:
118 
119  inline void rehash();
120  inline int nextPrime(int newCap) const ;
121  inline void accumulateAvgFill(int n) const ;
122 
123 
125  int count_;
127  mutable Value mostRecentValue_;
128  mutable Key mostRecentKey_;
129 
130  mutable size_t nHits_;
131  mutable double avgDegeneracy_;
133  };
134 
135  template<class Key, class Value>
136  std::string toString(const Hashtable<Key, Value>& h);
137 
141  template<class Key, class Value>
142  std::ostream& operator<<(std::ostream& os, const Hashtable<Key, Value>& h);
143 
144  template<class Key, class Value> inline
145  Hashtable<Key, Value>::Hashtable(int capacity, double rehashDensity)
146  : data_(), count_(0), capacity_(HashUtils::nextPrime(capacity)),
147  nHits_(0), avgDegeneracy_(0), rehashDensity_(rehashDensity)
148  {
149  data_.resize(capacity_);
150  }
151 
152  template<class Key, class Value> inline
153  bool Hashtable<Key, Value>::containsKey(const Key& key) const
154  {
155  const Array<HashPair<Key, Value> >& candidates
156  = data_[hashCode(key) % capacity_];
157 
158  for (int i=0; i<candidates.length(); i++)
159  {
160  const HashPair<Key, Value>& c = candidates[i];
161  if (c.key_ == key)
162  {
163  // (Key&) mostRecentKey_ = key;
164  //(Value&) mostRecentValue_ = c.value_;
165  return true;
166  }
167  }
168  return false;
169  }
170 
171  template<class Key, class Value> inline
172  void Hashtable<Key, Value>::put(const Key& key, const Value& value)
173  {
174  int index = hashCode(key) % capacity_;
175 
176  Array<HashPair<Key, Value> >& local = data_[index];
177 
178  // check for duplicate key
179  for (int i=0; i<local.length(); i++)
180  {
181  if (local[i].key_ == key)
182  {
183  local[i].value_ = value;
184  return;
185  }
186  }
187 
188  // no duplicate key, so increment element count by one.
189  count_++;
190 
191  // check for need to resize.
192  if ((double) count_ > rehashDensity_ * (double) capacity_)
193  {
194  capacity_ = HashUtils::nextPrime(capacity_+1);
195  rehash();
196  // recaluate index
197  index = hashCode(key) % capacity_;
198  }
199 
200  data_[index].append(HashPair<Key, Value>(key, value));
201  }
202 
203 
204 
205  template<class Key, class Value> inline
207  {
208  Array<Array<HashPair<Key, Value> > > tmp(capacity_);
209 
210  for (int i=0; i<data_.length(); i++)
211  {
212  for (int j=0; j<data_[i].length(); j++)
213  {
214  int newIndex = hashCode(data_[i][j].key_) % capacity_;
215  tmp[newIndex].append(data_[i][j]);
216  }
217  }
218 
219  data_ = tmp;
220  }
221 
222 
223  template<class Key, class Value> inline
225  {
226  keys.reserve(size());
227  values.reserve(size());
228 
229  for (int i=0; i<data_.length(); i++)
230  {
231  for (int j=0; j<data_[i].length(); j++)
232  {
233  keys.append(data_[i][j].key_);
234  values.append(data_[i][j].value_);
235  }
236  }
237  }
238 
239  template<class Key, class Value> inline
240  std::string Hashtable<Key, Value>::toString() const
241  {
242  Array<Key> keys;
243  Array<Value> values;
244  arrayify(keys, values);
245 
246  std::string rtn = "[";
247  for (int i=0; i<keys.length(); i++)
248  {
249  rtn += "{" + Teuchos::toString(keys[i]) + ", " + Teuchos::toString(values[i])
250  + "}";
251  if (i < keys.length()-1) rtn += ", ";
252  }
253  rtn += "]";
254 
255  return rtn;
256  }
257 
258  template<class Key, class Value> inline
259  std::string toString(const Hashtable<Key, Value>& h)
260  {
261  Array<Key> keys;
262  Array<Value> values;
263  h.arrayify(keys, values);
264 
265  std::string rtn = "[";
266  for (int i=0; i<keys.length(); i++)
267  {
268  rtn += "{" + Teuchos::toString(keys[i]) + ", " + Teuchos::toString(values[i])
269  + "}";
270  if (i < keys.length()-1) rtn += ", ";
271  }
272  rtn += "]";
273 
274  return rtn;
275  }
276 
277  template<class Key, class Value> inline
278  const Value& Hashtable<Key, Value>::get(const Key& key) const
279  {
280  TEUCHOS_TEST_FOR_EXCEPTION(!containsKey(key),
281  std::runtime_error,
282  "Hashtable<Key, Value>::get: key "
283  << Teuchos::toString(key)
284  << " not found in Hashtable"
285  << toString());
286 
287  const Array<HashPair<Key, Value> >& candidates
288  = data_[hashCode(key) % capacity_];
289 
290  accumulateAvgFill(candidates.length());
291 
292  for (int i=0; i<candidates.length(); i++)
293  {
294  const HashPair<Key, Value>& c = candidates[i];
295  if (c.key_ == key)
296  {
297  return c.value_;
298  }
299  }
300  return mostRecentValue_;
301  }
302 
303 
304  template<class Key, class Value> inline
305  void Hashtable<Key, Value>::remove(const Key& key)
306  {
307  TEUCHOS_TEST_FOR_EXCEPTION(!containsKey(key),
308  std::runtime_error,
309  "Hashtable<Key, Value>::remove: key "
310  << Teuchos::toString(key)
311  << " not found in Hashtable"
312  << toString());
313 
314  count_--;
315  int h = hashCode(key) % capacity_;
316  const Array<HashPair<Key, Value> >& candidates = data_[h];
317 
318  for (int i=0; i<candidates.length(); i++)
319  {
320  const HashPair<Key, Value>& c = candidates[i];
321  if (c.key_ == key)
322  {
323  data_[h].remove(i);
324  break;
325  }
326  }
327  }
328 
329  template<class Key, class Value> inline
331  {
332  avgDegeneracy_ = ((double) nHits_)/(nHits_ + 1.0) * avgDegeneracy_ + ((double) n)/(nHits_ + 1.0);
333  nHits_++;
334  }
335 
336  template<class Key, class Value> inline
337  std::ostream& operator<<(std::ostream& os, const Hashtable<Key, Value>& h)
338  {
339  return os << toString(h);
340  }
341 
342 
343 }
344 
345 #endif // TEUCHOS_HASHTABLE_H
void remove(int i)
Remove the i-th element from the array, with optional boundschecking.
Templated hashtable class.
void reserve(size_type n)
Utilities for generating hashcodes.
Array< T > & append(const T &x)
Add a new entry at the end of the array.
void arrayify(Array< Key > &keys, Array< Value > &values) const
Get lists of keys and values in Array form.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
Teuchos header file which uses auto-configuration information to include necessary C++ headers...
HashPair()
Empty constructor.
static int nextPrime(int newCapacity)
Value value_
Templated value variable.
std::string toString() const
Write to a std::string.
double avgDegeneracy() const
Return the average degeneracy (average number of entries per hash code).
Array< Array< HashPair< Key, Value > > > data_
double density() const
Return the density of the hashtable (num entries / capacity)
std::string toString(const HashSet< Key > &h)
bool containsKey(const Key &key) const
Check for the presence of a key.
Hashtable(int capacity=101, double rehashDensity=0.8)
Create an empty Hashtable.
Templated array class derived from the STL std::vector.
int nextPrime(int newCap) const
void put(const Key &key, const Value &value)
Put a new (key, value) pair in the table.
int length() const
Return number of elements in the array.
void setRehashDensity(double rehashDensity)
Set the density at which to do a rehash.
Helper class for Teuchos::Hashtable, representing a single &lt;key, value&gt; pair.
Utilities for generating hashcodes.
void accumulateAvgFill(int n) const
HashPair(const Key &key, const Value &value)
Basic &lt;key, value&gt; constructor.
const Value & get(const Key &key) const
Get the value indexed by key.
int size() const
Get the number of elements in the table.
void remove(const Key &key)
Remove from the table the element given by key.
Memory-safe templated array class that encapsulates std::vector.
Key key_
Templated key variable.