multimapwdef.h

00001 #ifndef MULTIMAPWDEF
00002 #define MULTIMAPWDEF
00003 
00004 #include <map>
00005 
00006 SWORD_NAMESPACE_START
00007 
00008 // multmap that still lets you use [] to reference FIRST
00009 // entry of a key if multiples exist
00010 template <class Key, class T, class Compare>
00011 class multimapwithdefault : public std::multimap<Key, T, Compare> {
00012 public:
00013         typedef std::pair<const Key, T> value_type;
00014         T& getWithDefault(const Key& k, const T& defaultValue) {
00015                 if (find(k) == this->end()) {
00016                         insert(value_type(k, defaultValue));
00017                 }
00018                 return (*(find(k))).second;
00019         }
00020 
00021         T& operator[](const Key& k) {
00022                 if (find(k) == this->end()) {
00023                         insert(value_type(k, T()));
00024                 }
00025                 return (*(find(k))).second;
00026         }
00027         bool has(const Key& k, const T &val) const {
00028                 typename std::multimap<Key, T, Compare>::const_iterator start = lower_bound(k);
00029                 typename std::multimap<Key, T, Compare>::const_iterator end = upper_bound(k);
00030                 for (; start!=end; start++) {
00031                         if (start->second == val)
00032                                 return true;
00033                 }
00034                 return false;
00035         }
00036 };
00037 
00038 SWORD_NAMESPACE_END
00039 #endif