Predator  [unstable] git snapshot
sympred.hh
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2011 Kamil Dudka <kdudka@redhat.com>
3  *
4  * This file is part of predator.
5  *
6  * predator is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * any later version.
10  *
11  * predator is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with predator. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef H_GUARD_SYM_PRED_H
21 #define H_GUARD_SYM_PRED_H
22 
23 #include "config.h"
24 #include "util.hh"
25 
26 #include <map>
27 #include <set>
28 
29 /// a symmetric relation
30 template <class TKey, bool IREFLEXIVE>
31 class SymPairSet {
32  protected:
33  typedef std::pair<TKey /* lt */, TKey /* gt */> TItem;
34  typedef std::set<TItem> TCont;
36 
37  public:
38  bool empty() const {
39  return cont_.empty();
40  }
41 
42  bool chk(TKey k1, TKey k2) const {
43  sortValues(k1, k2);
44  const TItem item(k1, k2);
45  return hasKey(cont_, item);
46  }
47 
48  bool add(TKey k1, TKey k2) {
49  CL_BREAK_IF(IREFLEXIVE && k1 == k2);
50 
51  sortValues(k1, k2);
52  const TItem item(k1, k2);
53  return cont_.insert(item)./* inserted */second;
54  }
55 
56  bool del(TKey k1, TKey k2) {
57  CL_BREAK_IF(IREFLEXIVE && k1 == k2);
58 
59  sortValues(k1, k2);
60  const TItem item(k1, k2);
61  return !!cont_.erase(item);
62  }
63 };
64 
65 template <class TKey, class TVal>
66 class SymPairMap {
67  protected:
68  typedef std::pair<TKey /* lt */, TKey /* gt */> TItem;
69  typedef std::map<TItem, TVal> TMap;
71 
72  public:
73  // for compatibility with STL and Boost libraries
74  typedef typename TMap::const_iterator const_iterator;
75  typedef typename TMap::const_reference const_reference;
76 
77  /// return STL-like iterator to go through the container
78  const_iterator begin() const { return db_.begin(); }
79 
80  /// return STL-like iterator to go through the container
81  const_iterator end() const { return db_.end(); }
82 
83  public:
84  void add(TKey k1, TKey k2, TVal val) {
85  sortValues(k1, k2);
86  const TItem key(k1, k2);
87 
88  CL_BREAK_IF(hasKey(db_, key));
89  db_[key] = val;
90  }
91 
92  bool chk(TVal *pDst, TKey k1, TKey k2) const {
93  sortValues(k1, k2);
94  const TItem key(k1, k2);
95 
96  typename TMap::const_iterator it = db_.find(key);
97  if (db_.end() == it)
98  return false;
99 
100  *pDst = it->second;
101  return true;
102  }
103 };
104 
105 #endif /* H_GUARD_SYM_PRED_H */