CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_0/src/FWCore/Utilities/interface/Map.h

Go to the documentation of this file.
00001 #ifndef FWCore_Utilities_Map_h
00002 #define FWCore_Utilities_Map_h
00003 
00004 #include <cassert>
00005 #include <map>
00006 
00007 // Alternatives to std::map::operator[]
00008 // They differ on what happens if the element is not in the map.
00009 // Those that do not insert into the map will also work on a const map.
00010 
00011 namespace edm {
00012 
00013   // This silly little function documents the fact
00014   // a possible insert into the map is intentional.
00015   template <typename Key, typename Value>
00016   inline
00017   Value&
00018   findOrInsert(std::map<Key, Value>& m, Key const& k) {
00019     return m[k];
00020   }
00021 
00022   // This function will not insert into the map.
00023   // If the element is not found, it returns the supplied default value
00024   // Comes in const and non-const versions
00025   template <typename Key, typename Value>
00026   inline
00027   Value const&
00028   findOrDefault(std::map<Key, Value> const& m, Key const& k, Value const& defaultValue) {
00029     typename std::map<Key, Value>::const_iterator it = m.find(k);
00030     return (it == m.end() ? defaultValue : it->second);
00031   }
00032 
00033   template <typename Key, typename Value>
00034   inline
00035   Value&
00036   findOrDefault(std::map<Key, Value>& m, Key const& k, Value& defaultValue) {
00037     typename std::map<Key, Value>::const_iterator it = m.find(k);
00038     return (it == m.end() ? defaultValue : it->second);
00039   }
00040 
00041   // This function will not insert into the map.
00042   // If the element is not found, it returns a default constructed value
00043   // Note that the return is by value, so if the element is found, it is copied.
00044   template <typename Key, typename Value>
00045   inline
00046   Value
00047   findOrDefault(std::map<Key, Value> const& m, Key const& k) {
00048     typename std::map<Key, Value>::const_iterator it = m.find(k);
00049     return (it == m.end() ? Value() : it->second);
00050   }
00051 
00052   // This function will not insert into the map.
00053   // If the element is not found, it asserts.
00054   // Comes in const and non-const versions
00055   template <typename Key, typename Value>
00056   inline
00057   Value const&
00058   findOrAssert(std::map<Key, Value> const& m, Key const& k) {
00059     typename std::map<Key, Value>::const_iterator it = m.find(k);
00060     if (it == m.end()) assert("findOrAssert" && 0);
00061     return it->second;
00062   }
00063 
00064   template <typename Key, typename Value>
00065   inline
00066   Value&
00067   findOrAssert(std::map<Key, Value>& m, Key const& k) {
00068     typename std::map<Key, Value>::const_iterator it = m.find(k);
00069     if (it == m.end()) assert("findOrAssert" && 0);
00070     return it->second;
00071   }
00072 }
00073 #endif