DefaultMap.h
Go to the documentation of this file.
00001 #ifndef DEFAULTMAP_E8UQ8T6
00002 #define DEFAULTMAP_E8UQ8T6
00003 
00004 /*
00005 File: DefaultMap.h
00006 Author: Samuel Barrett
00007 Description: a map that returns a default value without inserting when get is called.
00008 Created:  2011-08-23
00009 Modified: 2011-12-13
00010 */
00011 
00012 //#define DEFAULTMAP_USE_BOOST
00013 
00014 #ifdef DEFAULTMAP_USE_BOOST
00015 #include <boost/unordered_map.hpp>
00016 #else
00017 #include <map>
00018 #endif
00019 
00020 template <class Key, class T>
00021 class DefaultMap {
00022 public:
00023 #ifdef DEFAULTMAP_USE_BOOST
00024   typedef typename boost::unordered_map<Key,T>::const_iterator const_iterator;
00025   typedef typename boost::unordered_map<Key,T>::iterator iterator;
00026 #else
00027   typedef typename std::map<Key,T>::const_iterator const_iterator;
00028   typedef typename std::map<Key,T>::iterator iterator;
00029 #endif
00030   DefaultMap(T defaultValue):
00031     defaultValue(defaultValue)
00032   {}
00033 
00034   T get(const Key &key) const {
00035 #ifdef DEFAULTMAP_USE_BOOST
00036     typename boost::unordered_map<Key,T>::const_iterator it = vals.find(key);
00037 #else
00038     typename std::map<Key,T>::const_iterator it = vals.find(key);
00039 #endif
00040     if (it == vals.end())
00041       return defaultValue;
00042     else
00043       return it->second;
00044   }
00045 
00046   T& operator[](const Key &key) {
00047     if (vals.count(key) == 0)
00048       vals[key] = defaultValue;
00049     return vals[key];
00050   }
00051 
00052   void set(const Key &key, const T &val) {
00053     vals[key] = val;
00054   }
00055 
00056   void clear() {
00057     vals.clear();
00058   }
00059 
00060   void erase(iterator position) {
00061     vals.erase(position);
00062   }
00063 
00064   size_t erase(const Key &key) {
00065     return vals.erase(key);
00066   }
00067 
00068   unsigned int size() {
00069     return vals.size();
00070   }
00071 
00072   const_iterator begin() const {
00073     return vals.begin();
00074   }
00075   
00076   iterator begin() {
00077     return vals.begin();
00078   }
00079   
00080   const_iterator end() const {
00081     return vals.end();
00082   }
00083   
00084   iterator end() {
00085     return vals.end();
00086   }
00087 
00088 private:
00089 #ifdef DEFAULTMAP_USE_BOOST
00090   boost::unordered_map<Key,T> vals;
00091 #else
00092   std::map<Key,T> vals;
00093 #endif
00094   const T defaultValue;
00095 };
00096 
00097 #endif /* end of include guard: DEFAULTMAP_E8UQ8T6 */


bwi_tools
Author(s): Piyush Khandelwal
autogenerated on Thu Jun 6 2019 17:57:26