Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:13:12

0001 #ifndef FWCore_Utilities_Map_h
0002 #define FWCore_Utilities_Map_h
0003 
0004 #include <cassert>
0005 #include <map>
0006 
0007 // Alternatives to std::map::operator[]
0008 // They differ on what happens if the element is not in the map.
0009 // Those that do not insert into the map will also work on a const map.
0010 
0011 namespace edm {
0012 
0013   // This silly little function documents the fact
0014   // a possible insert into the map is intentional.
0015   template <typename Key, typename Value>
0016   inline Value& findOrInsert(std::map<Key, Value>& m, Key const& k) {
0017     return m[k];
0018   }
0019 
0020   // This function will not insert into the map.
0021   // If the element is not found, it returns the supplied default value
0022   // Comes in const and non-const versions
0023   template <typename Key, typename Value>
0024   inline Value const& findOrDefault(std::map<Key, Value> const& m, Key const& k, Value const& defaultValue) {
0025     typename std::map<Key, Value>::const_iterator it = m.find(k);
0026     return (it == m.end() ? defaultValue : it->second);
0027   }
0028 
0029   template <typename Key, typename Value>
0030   inline Value& findOrDefault(std::map<Key, Value>& m, Key const& k, Value& defaultValue) {
0031     typename std::map<Key, Value>::const_iterator it = m.find(k);
0032     return (it == m.end() ? defaultValue : it->second);
0033   }
0034 
0035   // This function will not insert into the map.
0036   // If the element is not found, it returns a default constructed value
0037   // Note that the return is by value, so if the element is found, it is copied.
0038   template <typename Key, typename Value>
0039   inline Value findOrDefault(std::map<Key, Value> const& m, Key const& k) {
0040     typename std::map<Key, Value>::const_iterator it = m.find(k);
0041     return (it == m.end() ? Value() : it->second);
0042   }
0043 
0044   // This function will not insert into the map.
0045   // If the element is not found, it asserts.
0046   // Comes in const and non-const versions
0047   template <typename Key, typename Value>
0048   inline Value const& findOrAssert(std::map<Key, Value> const& m, Key const& k) {
0049     typename std::map<Key, Value>::const_iterator it = m.find(k);
0050     if (it == m.end())
0051       assert("findOrAssert" && 0);
0052     return it->second;
0053   }
0054 
0055   template <typename Key, typename Value>
0056   inline Value& findOrAssert(std::map<Key, Value>& m, Key const& k) {
0057     typename std::map<Key, Value>::const_iterator it = m.find(k);
0058     if (it == m.end())
0059       assert("findOrAssert" && 0);
0060     return it->second;
0061   }
0062 }  // namespace edm
0063 #endif