|
1 /* -*- C++ -*- |
|
2 * src/lemon/map_utils.h - Part of LEMON, a generic C++ optimization library |
|
3 * |
|
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
|
5 * (Egervary Combinatorial Optimization Research Group, EGRES). |
|
6 * |
|
7 * Permission to use, modify and distribute this software is granted |
|
8 * provided that this copyright notice appears in all copies. For |
|
9 * precise terms see the accompanying LICENSE file. |
|
10 * |
|
11 * This software is provided "AS IS" with no warranty of any kind, |
|
12 * express or implied, and with no claim as to its suitability for any |
|
13 * purpose. |
|
14 * |
|
15 */ |
|
16 |
|
17 ///\ingroup gutils |
|
18 ///\file |
|
19 ///\brief Map utilities. |
|
20 |
|
21 #include <map> |
|
22 |
|
23 |
|
24 namespace lemon { |
|
25 |
|
26 /// \addtogroup gutils |
|
27 /// @{ |
|
28 |
|
29 |
|
30 /// \brief General inversable map type. |
|
31 |
|
32 /// This type provides simple inversable map functions. |
|
33 /// The InversableMap wraps an arbitrary ReadWriteMap |
|
34 /// and if a key is setted to a new value then store it |
|
35 /// in the inverse map. |
|
36 template < |
|
37 typename _Graph, |
|
38 typename _Map, |
|
39 template <typename, typename> class _InvMap = std::Map |
|
40 > |
|
41 class InversableMap : protected _Map { |
|
42 |
|
43 public: |
|
44 |
|
45 typename _Map Map; |
|
46 typename _InvMap<Map::Value, Map::Key> InverseMap; |
|
47 |
|
48 typename _Map::Key Key; |
|
49 typename _Map::Value Value; |
|
50 typename _Map::ConstReference ConstReference; |
|
51 |
|
52 /// Constructor. |
|
53 |
|
54 /// Construct a new InversableMap for the graph. |
|
55 /// |
|
56 InversableMap(const Graph& graph) : Map(graph) {} |
|
57 |
|
58 /// The setter function of the map. |
|
59 |
|
60 /// It sets the map and the inverse map |
|
61 void set(const Key& key, const Value& val) { |
|
62 Value oldval = Map::operator[](key); |
|
63 InverseMap::iterator it = invMap.find(oldval); |
|
64 if (it != invMap.end() && it->second == key) { |
|
65 invMap.erase(it); |
|
66 } |
|
67 invMap.insert(make_pair(val, key)); |
|
68 Map::set(key, val); |
|
69 } |
|
70 |
|
71 ConstReference operator[](const Key&) const { |
|
72 return Map::operator[](key); |
|
73 } |
|
74 |
|
75 virtual void add(const Key&) { |
|
76 Map::add(key); |
|
77 } |
|
78 |
|
79 virtual void erase(const Key&) { |
|
80 Value val = Map::operator[](key); |
|
81 InverseMap::iterator it = invMap.find(val); |
|
82 if (it != invMap.end() && it->second == key) { |
|
83 invMap.erase(it); |
|
84 } |
|
85 Map::erase(key); |
|
86 } |
|
87 |
|
88 const InverseMap& inverse() const { |
|
89 return invMap; |
|
90 } |
|
91 |
|
92 |
|
93 private: |
|
94 InverseMap invMap; |
|
95 }; |
|
96 |
|
97 } |
|
98 |