More general version, support for C ++ 98/03 and more containers
It works with universal associative containers, the only parameter of the template is the container type itself.
Supported containers: std::map , std::multimap , std::unordered_map , std::unordered_multimap , wxHashMap , QMap , QMultiMap , QHash , QMultiHash , etc.
template<typename MAP> const typename MAP::mapped_type& get_with_default(const MAP& m, const typename MAP::key_type& key, const typename MAP::mapped_type& defval) { typename MAP::const_iterator it = m.find(key); if (it == m.end()) return defval; return it->second; }
Using:
std::map<int, std::string> t; t[1] = "one"; string s = get_with_default(t, 2, "unknown");
Here is a similar implementation using a wrapper class that looks more like a get() method of type dict in Python: https://github.com/hltj/wxMEdit/blob/master/src/xm/xm_utils.hpp
template<typename MAP> struct map_wrapper { typedef typename MAP::key_type K; typedef typename MAP::mapped_type V; typedef typename MAP::const_iterator CIT; map_wrapper(const MAP& m) :m_map(m) {} const V& get(const K& key, const V& default_val) const { CIT it = m_map.find(key); if (it == m_map.end()) return default_val; return it->second; } private: const MAP& m_map; }; template<typename MAP> map_wrapper<MAP> wrap_map(const MAP& m) { return map_wrapper<MAP>(m); }
Using:
std::map<int, std::string> t; t[1] = "one"; string s = wrap_map(t).get(2, "unknown");
jyw Nov 16 '14 at 15:56 2014-11-16 15:56
source share