00001
00007 #ifndef __POINTERMAP_H__
00008 #define __POINTERMAP_H__
00009
00010 #include <map>
00011 #include <string>
00012 using std::string;
00013 #include <algorithm>
00014 #include <functional>
00015
00016 #include "generic_stdlib.h"
00017 #include "pointerlookup.h"
00018
00019
00028 template<class T, class K=string, bool owns_objects=true>
00029 class PointerMap : public PointerLookup<T,K> {
00030 public:
00032 typedef PointerMap<T,K,owns_objects> self;
00033
00035 typedef K key_type;
00036
00038 typedef T* data_type;
00039
00041 typedef std::pair<const key_type, data_type> value_type;
00042
00044 typedef std::map< key_type, data_type > map_type;
00045
00047 typedef typename map_type::iterator iterator;
00048
00050 typedef typename map_type::const_iterator const_iterator;
00051
00053 typedef typename map_type::size_type size_type;
00054
00055
00056 PointerMap() { }
00057 virtual ~PointerMap() { erase(); }
00058
00062 PointerMap(const self& o) { assert(0); abort(); }
00063 self& operator=( const self& o) { assert(0); abort(); }
00064
00066 iterator begin() { return m.begin(); }
00067 const_iterator begin() const { return m.begin(); }
00068 iterator end() { return m.end(); }
00069 const_iterator end() const { return m.end(); }
00071 std::pair<iterator,bool> insert(const value_type& x) { return m.insert(x); }
00072
00080 void set(const key_type& k, const data_type d) {
00081 iterator existing = m.find(k);
00082 if (existing == end())
00083 insert(Generic::make_pair_leftconst(k,d));
00084 else {
00085 if (owns_objects) delete (*existing).second;
00086 (*existing).second=d;
00087 }
00088 }
00089
00090
00095 T* getptr(const key_type& k) {
00096 const_iterator existing = m.find(k);
00097 return (existing == end() ? 0 : (*existing).second);
00098 }
00099
00101 const T* getptr(const key_type& k) const {
00102 const_iterator existing = m.find(k);
00103 return (existing == end() ? 0 : (*existing).second);
00104 }
00105
00106
00107
00108
00110 void erase() {
00111 if (owns_objects)
00112 Generic::delete_contents(m);
00113 else
00114 m.erase(m.begin(),m.end());
00115 }
00116
00118 void erase(const key_type& k) {
00119 T* ptr = getptr(k);
00120 if (ptr) {
00121 if (owns_objects) delete ptr;
00122 m.erase(k);
00123 }
00124 }
00125
00127 size_type size() { return m.size(); }
00128
00129 protected:
00131 map_type m;
00132 };
00133
00134
00135
00136
00139 template <class BaseType, class TableType=PointerMap<BaseType> >
00140 class HasTable {
00141 public:
00142 typedef TableType Table;
00143 typedef typename Table::key_type key_type;
00144
00149 void table_set(const key_type& name, BaseType* i) {
00150 assert (i); assert (name!=key_type());
00151 table_.set(name,i);
00152 }
00153
00154 const Table& table() const { return table_; }
00155
00156 private:
00158 Table table_;
00159 };
00160
00161
00162 #endif