aGrUM  0.21.0
a C++ library for (probabilistic) graphical models
integerVariable.cpp
Go to the documentation of this file.
1 /**
2  *
3  * Copyright (c) 2005-2021 by Pierre-Henri WUILLEMIN(@LIP6) & Christophe GONZALES(@AMU)
4  * info_at_agrum_dot_org
5  *
6  * This library is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This library 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 Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this library. If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 
22 #include <agrum/tools/variables/integerVariable.h>
23 
24 #ifdef GUM_NO_INLINE
25 # include <agrum/tools/variables/integerVariable_inl.h>
26 #endif /* GUM_NO_INLINE */
27 
28 namespace gum {
29 
30  /// constructor assigning a domain to the variable
32  const std::string& aDesc,
33  const std::vector< int >& domain) :
35  // get the values in increasing order
36  std::vector< int > dom = domain;
37  std::sort(dom.begin(), dom.end());
38 
39  // store the sorted values into a sequence
41  for (const int val : dom) {
42  _domain_ << val;
43  }
44 
45  // for debugging purposes
47  }
48 
49 
50  /// equality operator
51  bool IntegerVariable::operator==(const Variable& var) const {
52  try {
53  const IntegerVariable& xvar = dynamic_cast<const IntegerVariable&>(var);
54  return Variable::operator==(var) && (xvar._domain_ == _domain_);
55  } catch (std::bad_cast&) {
56  return false;
57  }
58  }
59 
60 
61  /// Returns the domain as a string
62  const std::string IntegerVariable::domain() const {
64  s << "<";
65 
66  const Size size = domainSize();
67  if (size > 0) {
68  s << _domain_[0];
69 
70  for (Idx i = 1; i < size; ++i) {
71  s << ',' << _domain_[i];
72  }
73  }
74 
75  s << ">";
76 
77  return s.str();
78  }
79 
80 
81  /// add a new value to the domain size
83  const Size size = _domain_.size();
84  if (size == Size(0) || (_domain_[size - 1] < value)) {
86  } else {
87  // here, the value must not be inserted at the end of the sequence.
88  // it is faster to reconstruct the sequence from scratch
89  std::vector< int > values;
90  values.reserve(_domain_.size() + 1);
91  for (const auto val: _domain_)
94  std::sort(values.begin(), values.end());
95 
96  Sequence< int > new_domain(_domain_.size() + 1);
97  for (const auto val: values)
100  }
101 
102  return *this;
103  }
104 
105 } // namespace gum
INLINE void emplace(Args &&... args)
Definition: set_tpl.h:643