ROSE  0.11.96.11
Map.h
1 #ifndef ROSE_Map_H
2 #define ROSE_Map_H
3 
4 #include <stdexcept>
5 #include <map>
6 #include <boost/optional.hpp>
7 
9 template<class Key, class T, class Compare=std::less<Key>, class Alloc=std::allocator<std::pair<const Key, T> > >
10 class Map: public std::map<Key, T, Compare, Alloc> {
11 public:
12  typedef std::map<Key, T, Compare, Alloc> map_type;
13 
14 #ifdef ROSE_HAVE_BOOST_SERIALIZATION_LIB
15 private:
16  friend class boost::serialization::access;
17 
18  template<class S>
19  void serialize(S &s, const unsigned /*version*/) {
20  s & BOOST_SERIALIZATION_BASE_OBJECT_NVP(map_type);
21  }
22 #endif
23 
24 public:
25  // Constructors are the same as for std::map
26  Map() {}
27 
28  explicit Map(const Compare& comp, const Alloc& alloc = Alloc())
29  : map_type(comp, alloc) {}
30 
31  template <class InputIterator>
32  Map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const Alloc& alloc = Alloc())
33  : map_type(first, last, comp, alloc) {};
34 
35  Map(const Map& other)
36  : map_type(other) {}
37 
49  boost::optional<T> get(const Key &key) const {
50  typename map_type::const_iterator found = this->find(key);
51  return found==this->end() ? boost::optional<T>() : boost::optional<T>(found->second);
52  }
53 
58  const T& get_one(const Key &key) const {
59  typename map_type::const_iterator found = this->find(key);
60  if (found==this->end())
61  throw std::domain_error("key not present in map");
62  return found->second;
63  }
64  T& get_one(const Key &key) {
65  typename map_type::iterator found = this->find(key);
66  if (found==this->end())
67  throw std::domain_error("key not present in map");
68  return found->second;
69  }
75  const T& get_value_or(const Key& key, const T& dflt) const {
76  typename map_type::const_iterator found = this->find(key);
77  return found==this->end() ? dflt : found->second;
78  }
79  T& get_value_or(const Key& key, T& dflt) {
80  typename map_type::iterator found = this->find(key);
81  return found==this->end() ? dflt : found->second;
82  }
89  bool exists(const Key &key) const { return this->find(key)!=this->end(); }
90 };
91 
92 #endif
Map::get_one
T & get_one(const Key &key)
Look up one value or throw an exception.
Definition: Map.h:64
Map::get
boost::optional< T > get(const Key &key) const
Lookup and return a value or nothing.
Definition: Map.h:49
Map::exists
bool exists(const Key &key) const
Convenience for determining if a key exists in this map.
Definition: Map.h:89
Map::get_one
const T & get_one(const Key &key) const
Look up one value or throw an exception.
Definition: Map.h:58
Map::get_value_or
const T & get_value_or(const Key &key, const T &dflt) const
Convenience for getting a value from an Option.
Definition: Map.h:75
Map::get_value_or
T & get_value_or(const Key &key, T &dflt)
Convenience for getting a value from an Option.
Definition: Map.h:79
Map
Extends std::map with methods that return optional values.
Definition: Map.h:10