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