aGrUM  0.18.1
a C++ library for (probabilistic) graphical models
gum::HashTable< Key, Val, Alloc > Class Template Reference

The class for generic Hash Tables. More...

#include <agrum/tools/core/hashTable.h>

+ Collaboration diagram for gum::HashTable< Key, Val, Alloc >:

Public Member Functions

template<typename... Args>
INLINE HashTable< Key, Val, Alloc >::value_typeemplace (Args &&... args)
 
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE map (Mount(*f)(Val), Size size, bool resize_pol, bool key_uniqueness_pol) const
 
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE map (Mount(*f)(Val &), Size size, bool resize_pol, bool key_uniqueness_pol) const
 
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE map (Mount(*f)(const Val &), Size size, bool resize_pol, bool key_uniqueness_pol) const
 
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE map (const Mount &val, Size size, bool resize_pol, bool key_uniqueness_pol) const
 
template<typename OtherAlloc >
INLINE bool operator!= (const HashTable< Key, Val, OtherAlloc > &from) const
 
Constructors / Destructors
 HashTable (Size size_param=HashTableConst::default_size, bool resize_pol=HashTableConst::default_resize_policy, bool key_uniqueness_pol=HashTableConst::default_uniqueness_policy)
 Default constructor. More...
 
 HashTable (std::initializer_list< std::pair< Key, Val > > list)
 Initializer list constructor. More...
 
 HashTable (const HashTable< Key, Val, Alloc > &from)
 Copy constructor. More...
 
template<typename OtherAlloc >
 HashTable (const HashTable< Key, Val, OtherAlloc > &from)
 Generalized copy constructor. More...
 
 HashTable (HashTable< Key, Val, Alloc > &&from)
 Move constructor. More...
 
 ~HashTable ()
 Class destructor. More...
 
Operators
HashTable< Key, Val, Alloc > & operator= (const HashTable< Key, Val, Alloc > &from)
 Copy operator. More...
 
template<typename OtherAlloc >
HashTable< Key, Val, Alloc > & operator= (const HashTable< Key, Val, OtherAlloc > &from)
 Generalized copy operator. More...
 
HashTable< Key, Val, Alloc > & operator= (HashTable< Key, Val, Alloc > &&from)
 Move operator. More...
 
Val & operator[] (const Key &key)
 Returns a reference on the value the key of which is passed in argument. More...
 
const Val & operator[] (const Key &key) const
 returns a reference on the value the key of which is passed in argument More...
 
template<typename OtherAlloc >
bool operator== (const HashTable< Key, Val, OtherAlloc > &from) const
 Checks whether two hashtables contain the same elements. More...
 
template<typename OtherAlloc >
bool operator!= (const HashTable< Key, Val, OtherAlloc > &from) const
 Checks whether two hashtables contain different sets of elements. More...
 
Fine tuning
Size capacity () const noexcept
 Returns the number of slots in the 'nodes' vector of the hashtable. More...
 
void resize (Size new_size)
 Changes the number of slots in the 'nodes' vector of the hash table. More...
 
void setResizePolicy (const bool new_policy) noexcept
 Enables the user to change dynamically the resizing policy. More...
 
bool resizePolicy () const noexcept
 Returns the current resizing policy. More...
 
void setKeyUniquenessPolicy (const bool new_policy) noexcept
 Enables the user to change dynamically the policy for checking whether there can exist several elements in the table with identical keys. More...
 
bool keyUniquenessPolicy () const noexcept
 Returns the current checking policy. More...
 
Accessors / Modifiers
Size size () const noexcept
 Returns the number of elements stored into the hashtable. More...
 
bool exists (const Key &key) const
 Checks whether there exists an element with a given key in the hashtable. More...
 
value_typeinsert (const Key &key, const Val &val)
 Adds a new element (actually a copy of this element) into the hash table. More...
 
value_typeinsert (Key &&key, Val &&val)
 Moves a new element in the hash table. More...
 
value_typeinsert (const std::pair< Key, Val > &elt)
 Adds a new element (actually a copy of this element) into the hash table. More...
 
value_typeinsert (std::pair< Key, Val > &&elt)
 Moves a new element in the hash table. More...
 
template<typename... Args>
value_typeemplace (Args &&... args)
 Emplace a new element into the hashTable. More...
 
mapped_typegetWithDefault (const Key &key, const Val &default_value)
 Returns a reference on the element the key of which is passed in argument. More...
 
mapped_typegetWithDefault (Key &&key, Val &&default_value)
 Returns a reference on the element the key of which is passed in argument. More...
 
void set (const Key &key, const Val &default_value)
 Add a new property or modify it if it already existed. More...
 
void reset (const Key &key)
 Removes a property (i.e., remove an element). More...
 
void erase (const Key &key)
 Removes a given element from the hash table. More...
 
void erase (const iterator_safe &iter)
 Removes a given element from the hash table. More...
 
void erase (const const_iterator_safe &iter)
 Removes a given element from the hash table. More...
 
void eraseByVal (const Val &val)
 Removes a given element from the hash table. More...
 
const Key & keyByVal (const Val &val) const
 Returns a reference on the key given a value. More...
 
const Key & key (const Key &key) const
 Returns a reference on a given key. More...
 
void eraseAllVal (const Val &val)
 Removes all the elements having a certain value from the hash table. More...
 
void clear ()
 Removes all the elements in the hash table. More...
 
bool empty () const noexcept
 Indicates whether the hash table is empty. More...
 
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > map (Mount(*f)(Val), Size size=Size(0), bool resize_pol=HashTableConst::default_resize_policy, bool key_uniqueness_pol=HashTableConst::default_uniqueness_policy) const
 Transforms a hashtable of vals into a hashtable of mountains. More...
 
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > map (Mount(*f)(Val &), Size size=Size(0), bool resize_pol=HashTableConst::default_resize_policy, bool key_uniqueness_pol=HashTableConst::default_uniqueness_policy) const
 Transforms a hashtable of vals into a hashtable of mountains. More...
 
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > map (Mount(*f)(const Val &), Size size=Size(0), bool resize_pol=HashTableConst::default_resize_policy, bool key_uniqueness_pol=HashTableConst::default_uniqueness_policy) const
 Transforms a hashtable of vals into a hashtable of mountains. More...
 
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > map (const Mount &val, Size size=Size(0), bool resize_pol=HashTableConst::default_resize_policy, bool key_uniqueness_pol=HashTableConst::default_uniqueness_policy) const
 Creates a hashtable of mounts with a given value from a hashtable of vals. More...
 

Public Types

using Bucket = HashTableBucket< Key, Val >
 The buckets where data are stored. More...
 
using BucketAllocator = typename Alloc::template rebind< Bucket >::other
 The Bucket allocator. More...
 
using key_type = Key
 Types for STL compliance. More...
 
using mapped_type = Val
 Types for STL compliance. More...
 
using value_type = std::pair< const Key, Val >
 Types for STL compliance. More...
 
using reference = value_type &
 Types for STL compliance. More...
 
using const_reference = const value_type &
 Types for STL compliance. More...
 
using pointer = value_type *
 Types for STL compliance. More...
 
using const_pointer = const value_type *
 Types for STL compliance. More...
 
using size_type = Size
 Types for STL compliance. More...
 
using difference_type = std::ptrdiff_t
 Types for STL compliance. More...
 
using allocator_type = Alloc
 Types for STL compliance. More...
 
using iterator = HashTableIterator< Key, Val >
 Types for STL compliance. More...
 
using const_iterator = HashTableConstIterator< Key, Val >
 Types for STL compliance. More...
 
using iterator_safe = HashTableIteratorSafe< Key, Val >
 Types for STL compliance. More...
 
using const_iterator_safe = HashTableConstIteratorSafe< Key, Val >
 Types for STL compliance. More...
 

Friends

template<typename K , typename V , typename A >
class HashTable
 Friends to optimize the access to data, iterators must be friends. More...
 
class HashTableIterator< Key, Val >
 Friends to optimize the access to data, iterators must be friends. More...
 
class HashTableConstIterator< Key, Val >
 Friends to optimize the access to data, iterators must be friends. More...
 
class HashTableIteratorSafe< Key, Val >
 Friends to optimize the access to data, iterators must be friends. More...
 
class HashTableConstIteratorSafe< Key, Val >
 Friends to optimize the access to data, iterators must be friends. More...
 
template<typename T1 , typename T2 , typename A >
class Bijection
 For bijections to quickly access data. More...
 
std::ostream & operator<< (std::ostream &, const HashTable< Key, Val, Alloc > &)
 Prints the content of a gum::HashTable in the stream. More...
 
std::ostream & operator<< (std::ostream &s, const HashTable< Key *, Val, Alloc > &table)
 Prints the content of a gum::HashTable with pointers key in the stream. More...
 

Iterators

const iteratorend () noexcept
 Returns the unsafe iterator pointing to the end of the hashtable. More...
 
const const_iteratorend () const noexcept
 Returns the unsafe const_iterator pointing to the end of the hashtable. More...
 
const const_iteratorcend () const noexcept
 Returns the unsafe const_iterator pointing to the end of the hashtable. More...
 
iterator begin ()
 Returns an unsafe iterator pointing to the beginning of the hashtable. More...
 
const_iterator begin () const
 Returns an unsafe const_iterator pointing to the beginning of the hashtable. More...
 
const_iterator cbegin () const
 Returns an unsafe const_iterator pointing to the beginning of the hashtable. More...
 
const iterator_safeendSafe () noexcept
 Returns the safe iterator pointing to the end of the hashtable. More...
 
const const_iterator_safeendSafe () const noexcept
 Returns the safe const_iterator pointing to the end of the hashtable. More...
 
const const_iterator_safecendSafe () const noexcept
 Returns the safe const_iterator pointing to the end of the hashtable. More...
 
iterator_safe beginSafe ()
 Returns the safe iterator pointing to the beginning of the hashtable. More...
 
const_iterator_safe beginSafe () const
 Returns the safe const_iterator pointing to the beginning of the hashtable. More...
 
const_iterator_safe cbeginSafe () const
 Returns the safe const_iterator pointing to the beginning of the hashtable. More...
 
static const iteratorend4Statics ()
 Returns the end iterator for other classes' statics (read the detailed description of this method). More...
 
static const const_iteratorconstEnd4Statics ()
 Returns the end iterator for other classes' statics (read the detailed description of this method). More...
 
static const iterator_safeendSafe4Statics ()
 Returns the end iterator for other classes' statics (read the detailed description of this method). More...
 
static const const_iterator_safeconstEndSafe4Statics ()
 Returns the end iterator for other classes' statics (read the detailed description of this method). More...
 

Detailed Description

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
class gum::HashTable< Key, Val, Alloc >

The class for generic Hash Tables.

In aGrUM, a hashtable is a vector of chained lists (collision problems are fixed by chaining). Each slot of the vector contains a list of elements sharing the same hashed value. To be computationally efficient, the hash table should not contain too many elements as compared to its number of slots. Therefore, it is sometimes useful to resize the chained lists vector. aGrUM's hash tables are designed to automatically double their size when there is in average more than 3 elements per slot. However, when memory consumption is a concern, this feature can be turned off either by passing false as an optional resize_pol argument to the constructor of the hash table or by using method setResizePolicy when the instance of the class has already been constructed. Similarly, the default number of slots of the hash table may be parameterized as an optional argument of the constructor (size_param). Beware: when inserting elements of a given class into a hash table, unless the element is an r-value, only a copy of this element is stored into the table (this is compulsory if the hashtable is to be generic and can be used to store both complex classes and built-in types like integers). HashTable have different kinds of iterators: HashTableIteratorSafe and HashTableConstIteratorSafe (a.k.a. HashTable<>::iterator_safe and HashTable<>::const_iterator_safe) allow safe parsing of the hash tables. By safe, we mean that whenever the element pointed to by such an iterator is removed from the hashtable, accessing it through the iterator (*iter) does not result in a segmentation fault but rather in an exception being thrown. This safety is ensured at a very low cost (actually, our experiments show that our HashTables and HashTable's safe iterators significantly outperform the standard library unordered_maps). Of course, if there is no possibility for an iterator to point to a deleted element, the user can use "unsafe" iterators HashTableIterator and HashTableConstIterator (a.k.a. HashTable<>::iterator and HashTable<>::const_iterator). These iterators are slightly faster than their safe counterparts. However, as in the standard library, accessing through them a deleted element usually results in a mess (most probably a segfault).

Warning
HashTables guarantee that any element stored within them will have the same location in memory until it is removed from the hashtable (and this holds whatever operation is performed on the hashtable like new insertions, deletions, resizing, etc.).
Usage example:
// creation of an empty hash table
HashTable<int,string> table1;
// insert two elements into the hash table
table1.insert (10,"xxx");
table1.insert (20,"yyy");
table1.emplace (30,"zzz");
// creation of a nonempty hashtable using initializer lists
HashTable<int,bool> table { std::make_pair(3,true), std::make_pair(2,false)
};
// display the content of the hash table
cerr << table1;
// get the number of elements stored into the hash table
cerr << "number of elements in table1 = " << table1.size () << endl;
// create two copies of the hash table
HashTable<int,string> table2, table3 = table1;
table2 = table3;
// get the element whose key is 10
cerr << table1[10] << " = xxx" << endl;
// check whether there exists an element with key 20
if (table1.exists (20)) cerr << "element found" << endl;
// transform the hashtable of string into a hashtable of int assuming f is
// defined as: int f (const string& str) { return str.size (); }
HashTable<int,int> table = table1.map (f);
// remove two elements from table1 and table2
table1.erase (10); // key = 10
table1.eraseByVal ("yyy"); // val = "yyy"
table2.clear ();
// check whether the hash table is empty
if (!table1.empty ()) cerr << "table not empty" << endl;
// check wether hashtables contain the same elements
if ((table1 == table2) && (table1 != table3))
cerr << "check for equality/inequality" << endl;
// parse the content of a hashtable using an unsafe iterator
for (HashTable<int,string>::const_iterator iter = table1.cbegin();
iter != table1.cend(); ++iter)
cerr << *iter;
HashTable<int,string>::iterator iter = table1.begin();
iter += 2;
cerr << iter.key () << " " << iter.val ();
// use an iterator to point the element we wish to erase
HashTable<int,string>::iterator_safe iterS = table1.beginSafe ();
table1.erase ( table1.beginSafe () + 4 );
table1.erase ( iterS ); // this is safe because the iterator is safe
// check for iterator's safety
for (HashTable<int,string>::iterator_safe iter = table1.beginSafe ();
iter != table1.endSafe (); ++iter )
table1.eraseByVal ( *iter );
Template Parameters
KeyThe type for keys in a gum::HashTable.
ValThe type for values in a gum::HashTable.
AllocThe gum::HashTable allocator.

Definition at line 679 of file hashTable.h.

Member Typedef Documentation

◆ allocator_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::allocator_type = Alloc

Types for STL compliance.

Definition at line 692 of file hashTable.h.

◆ Bucket

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::Bucket = HashTableBucket< Key, Val >

The buckets where data are stored.

Definition at line 700 of file hashTable.h.

◆ BucketAllocator

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::BucketAllocator = typename Alloc::template rebind< Bucket >::other

The Bucket allocator.

Definition at line 703 of file hashTable.h.

◆ const_iterator

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::const_iterator = HashTableConstIterator< Key, Val >

Types for STL compliance.

Definition at line 694 of file hashTable.h.

◆ const_iterator_safe

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::const_iterator_safe = HashTableConstIteratorSafe< Key, Val >

Types for STL compliance.

Definition at line 696 of file hashTable.h.

◆ const_pointer

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::const_pointer = const value_type*

Types for STL compliance.

Definition at line 689 of file hashTable.h.

◆ const_reference

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::const_reference = const value_type&

Types for STL compliance.

Definition at line 687 of file hashTable.h.

◆ difference_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::difference_type = std::ptrdiff_t

Types for STL compliance.

Definition at line 691 of file hashTable.h.

◆ iterator

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::iterator = HashTableIterator< Key, Val >

Types for STL compliance.

Definition at line 693 of file hashTable.h.

◆ iterator_safe

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::iterator_safe = HashTableIteratorSafe< Key, Val >

Types for STL compliance.

Definition at line 695 of file hashTable.h.

◆ key_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::key_type = Key

Types for STL compliance.

Definition at line 683 of file hashTable.h.

◆ mapped_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::mapped_type = Val

Types for STL compliance.

Definition at line 684 of file hashTable.h.

◆ pointer

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::pointer = value_type*

Types for STL compliance.

Definition at line 688 of file hashTable.h.

◆ reference

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::reference = value_type&

Types for STL compliance.

Definition at line 686 of file hashTable.h.

◆ size_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::size_type = Size

Types for STL compliance.

Definition at line 690 of file hashTable.h.

◆ value_type

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
using gum::HashTable< Key, Val, Alloc >::value_type = std::pair< const Key, Val >

Types for STL compliance.

Definition at line 685 of file hashTable.h.

Constructor & Destructor Documentation

◆ HashTable() [1/5]

template<typename Key , typename Val , typename Alloc >
gum::HashTable< Key, Val, Alloc >::HashTable ( Size  size_param = HashTableConst::default_size,
bool  resize_pol = HashTableConst::default_resize_policy,
bool  key_uniqueness_pol = HashTableConst::default_uniqueness_policy 
)
explicit

Default constructor.

The true capacity (vector's size) of the hashtable will be the lowest number greater than or equal to size_param that is also a power of 2. The second optional argument is the resizing policy. By default, each time there is an average of 3 elements by node, the size of the hashtable is automatically multiplied by 2. But the user may pass false as argument to resize_pol to disable this feature.

Parameters
size_paramThe initial size of the gum::HashTable.
resize_polThe policy for resizing the hashtable when new elements are added (possible values: true = automatic resize and false = manual resize).
key_uniqueness_polUniqueness policy : should we prevent inserting the same key more than once in the table?

Definition at line 382 of file hashTable_tpl.h.

384  :
385  // size must be >= 2 else we lose all the bits of the hash function
386  size__{Size(1) << hashTableLog2__(std::max(Size(2), size_param))},
387  resize_policy__{resize_pol}, key_uniqueness_policy__{key_uniqueness_pol} {
388  // for debugging purposes
389  GUM_CONSTRUCTOR(HashTable);
390 
391  // finalize the creation
392  create__(size__);
393  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
unsigned int hashTableLog2__(const Size nb)
Returns the size in bits - 1 necessary to store the smallest power of 2 greater than or equal to nb...
void create__(Size size)
Used by all default constructors (general and specialized).
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ HashTable() [2/5]

template<typename Key, typename Val, typename Alloc >
gum::HashTable< Key, Val, Alloc >::HashTable ( std::initializer_list< std::pair< Key, Val > >  list)
explicit

Initializer list constructor.

Parameters
listThe initialized list.

Definition at line 396 of file hashTable_tpl.h.

397  :
398  // size must be >= 2 else we lose all the bits of the hash function
400  std::max< Size >(Size(2), Size(list.size()) / 2))} {
401  // for debugging purposes
402  GUM_CONSTRUCTOR(HashTable);
403 
404  // setup the nodes__ vector (contains only empty lists)
405  create__(size__);
406 
407  // insert all the elements
408  for (const auto& elt: list) {
409  insert(elt);
410  }
411  }
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
unsigned int hashTableLog2__(const Size nb)
Returns the size in bits - 1 necessary to store the smallest power of 2 greater than or equal to nb...
void create__(Size size)
Used by all default constructors (general and specialized).
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.

◆ HashTable() [3/5]

template<typename Key, typename Val, typename Alloc>
gum::HashTable< Key, Val, Alloc >::HashTable ( const HashTable< Key, Val, Alloc > &  from)

Copy constructor.

This creates a new hashtable the content of which is similar to that of the table passed in argument. Beware: similar does not mean that both tables share the same objects, but rather that the objects stored in the newly created table are copies of those of the table passed in argument. In particular, the new hash table inherits the parameters (resize policy, uniqueness policy) of table 'from'.

Parameters
fromThe gum::HashTable to copy.

Definition at line 414 of file hashTable_tpl.h.

415  :
416  size__{table.size__},
417  resize_policy__{table.resize_policy__},
418  key_uniqueness_policy__{table.key_uniqueness_policy__},
419  begin_index__{table.begin_index__} {
420  // for debugging purposes
421  GUM_CONS_CPY(HashTable);
422 
423  // setup the nodes__ vector (contains only empty lists)
424  create__(size__);
425 
426  // fill with the content of table
427  copy__(table);
428  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
void copy__(const HashTable< Key, Val, OtherAlloc > &table)
A function used to perform copies of HashTables.
void create__(Size size)
Used by all default constructors (general and specialized).
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721

◆ HashTable() [4/5]

template<typename Key, typename Val, typename Alloc >
template<typename OtherAlloc >
gum::HashTable< Key, Val, Alloc >::HashTable ( const HashTable< Key, Val, OtherAlloc > &  from)

Generalized copy constructor.

This creates a new hashtable the content of which is similar to that of the table passed in argument. Beware: similar does not mean that both tables share the same objects, but rather that the objects stored in the newly created table are copies of those of the table passed in argument. In particular, the new hash table inherits the parameters (resize policy, uniqueness policy) of table 'table'

Parameters
fromThe gum::HashTable to copy.

Definition at line 432 of file hashTable_tpl.h.

433  :
434  size__{table.size__},
435  resize_policy__{table.resize_policy__},
436  key_uniqueness_policy__{table.key_uniqueness_policy__},
437  begin_index__{table.begin_index__} {
438  // for debugging purposes
439  GUM_CONS_CPY(HashTable);
440 
441  // setup the nodes__ vector (contains only empty lists)
442  create__(size__);
443 
444  // fill with the content of table
445  copy__(table);
446  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
void copy__(const HashTable< Key, Val, OtherAlloc > &table)
A function used to perform copies of HashTables.
void create__(Size size)
Used by all default constructors (general and specialized).
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721

◆ HashTable() [5/5]

template<typename Key, typename Val, typename Alloc>
gum::HashTable< Key, Val, Alloc >::HashTable ( HashTable< Key, Val, Alloc > &&  from)

Move constructor.

Parameters
fromThe gum::HashTable to move.

Definition at line 449 of file hashTable_tpl.h.

449  :
450  nodes__(std::move(table.nodes__)), size__{table.size__},
451  nb_elements__{table.nb_elements__}, hash_func__{table.hash_func__},
452  resize_policy__{table.resize_policy__},
453  key_uniqueness_policy__{table.key_uniqueness_policy__},
454  begin_index__{table.begin_index__},
455  safe_iterators__(std::move(table.safe_iterators__)),
456  alloc__(std::move(table.alloc__)) {
457  // for debugging purposes
458  table.size__ = 0;
459  GUM_CONS_MOV(HashTable);
460  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
std::vector< HashTableConstIteratorSafe< Key, Val > *> safe_iterators__
The list of safe iterators pointing to the hash table.
Definition: hashTable.h:1753
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721

◆ ~HashTable()

template<typename Key , typename Val , typename Alloc >
INLINE gum::HashTable< Key, Val, Alloc >::~HashTable ( )

Class destructor.

Definition at line 484 of file hashTable_tpl.h.

484  {
485  // for debugging purposes
486  GUM_DESTRUCTOR(HashTable);
487 
488  // update all the registered iterators: they should now point to nullptr
489  // and their hashtable should be set to nullptr
491  }
void clearIterators__()
Clear all the safe iterators.
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698

Member Function Documentation

◆ begin() [1/2]

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::iterator gum::HashTable< Key, Val, Alloc >::begin ( )

Returns an unsafe iterator pointing to the beginning of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns an unsafe iterator pointing to the beginning of the hashtable.

Definition at line 635 of file hashTable_tpl.h.

Referenced by gum::Estimator< GUM_SCALAR >::confidence(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::learning::Miic::orientation_3off2_(), gum::learning::Miic::orientation_miic_(), and gum::SmallObjectAllocator::~SmallObjectAllocator().

635  {
636  // if the table is empty, make the begin and end point to the same element
637  if (nb_elements__ == Size(0))
638  return iterator{end()};
639  else
640  return iterator{*this};
641  }
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
HashTableIterator< Key, Val > iterator
Types for STL compliance.
Definition: hashTable.h:693
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ begin() [2/2]

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::const_iterator gum::HashTable< Key, Val, Alloc >::begin ( ) const

Returns an unsafe const_iterator pointing to the beginning of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns an unsafe const_iterator pointing to the beginning of the hashtable.

Definition at line 645 of file hashTable_tpl.h.

645  {
646  // if the table is empty, make the begin and end point to the same element
647  if (nb_elements__ == Size(0))
648  return const_iterator{end()};
649  else
650  return const_iterator{*this};
651  }
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
HashTableConstIterator< Key, Val > const_iterator
Types for STL compliance.
Definition: hashTable.h:694

◆ beginSafe() [1/2]

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::iterator_safe gum::HashTable< Key, Val, Alloc >::beginSafe ( )

Returns the safe iterator pointing to the beginning of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe iterator pointing to the beginning of the hashtable.

Definition at line 695 of file hashTable_tpl.h.

Referenced by gum::SetTerminalNodePolicy< GUM_SCALAR >::clearAllTerminalNodes(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::LeafAggregator::leavesMap(), gum::StructuredPlaner< double >::optimalPolicy2String(), gum::SetTerminalNodePolicy< GUM_SCALAR >::terminalNodeId(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::toDot(), gum::ITI< AttributeSelection, isScalar >::updateGraph(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::~IncrementalGraphLearner(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::~MultiDimFunctionGraphOperator(), and gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::~Regress().

695  {
696  // if the table is empty, make the begin and end point to the same element
697  if (nb_elements__ == Size(0))
698  return iterator_safe{endSafe()};
699  else
700  return iterator_safe{*this};
701  }
const iterator_safe & endSafe() noexcept
Returns the safe iterator pointing to the end of the hashtable.
HashTableIteratorSafe< Key, Val > iterator_safe
Types for STL compliance.
Definition: hashTable.h:695
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ beginSafe() [2/2]

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::const_iterator_safe gum::HashTable< Key, Val, Alloc >::beginSafe ( ) const

Returns the safe const_iterator pointing to the beginning of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe const_iterator pointing to the beginning of the hashtable.

Definition at line 705 of file hashTable_tpl.h.

705  {
706  // if the table is empty, make the begin and end point to the same element
707  if (nb_elements__ == Size(0))
708  return const_iterator_safe{endSafe()};
709  else
710  return const_iterator_safe{*this};
711  }
const iterator_safe & endSafe() noexcept
Returns the safe iterator pointing to the end of the hashtable.
HashTableConstIteratorSafe< Key, Val > const_iterator_safe
Types for STL compliance.
Definition: hashTable.h:696
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ capacity()

template<typename Key , typename Val , typename Alloc >
INLINE Size gum::HashTable< Key, Val, Alloc >::capacity ( ) const
noexcept

Returns the number of slots in the 'nodes' vector of the hashtable.

The method runs in constant time.

Returns
Returns the number of slots in the 'nodes' vector of the hashtable.

Definition at line 740 of file hashTable_tpl.h.

Referenced by gum::ArcGraphPart::ArcGraphPart().

740  {
741  return size__;
742  }
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
+ Here is the caller graph for this function:

◆ cbegin()

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::const_iterator gum::HashTable< Key, Val, Alloc >::cbegin ( ) const

Returns an unsafe const_iterator pointing to the beginning of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns an unsafe const_iterator pointing to the beginning of the hashtable.

Definition at line 655 of file hashTable_tpl.h.

Referenced by gum::DAGCycleDetector::addArc(), gum::DAGCycleDetector::addWeightedSet__(), gum::BijectionImplementation< Idx, const std::string *, std::allocator< const std::string * >, std::is_scalar< Idx >::value &&std::is_scalar< const std::string * >::value >::copy__(), gum::DAGCycleDetector::delWeightedSet__(), gum::DAGCycleDetector::eraseArc(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator+(), gum::DAGCycleDetector::restrictWeightedSet__(), gum::learning::StructuralConstraintSliceOrder::StructuralConstraintSliceOrder(), and gum::credal::InferenceEngine< GUM_SCALAR >::updateCredalSets_().

655  {
656  // if the table is empty, make the begin and end point to the same element
657  if (nb_elements__ == Size(0))
658  return const_iterator{cend()};
659  else
660  return const_iterator{*this};
661  }
const const_iterator & cend() const noexcept
Returns the unsafe const_iterator pointing to the end of the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
HashTableConstIterator< Key, Val > const_iterator
Types for STL compliance.
Definition: hashTable.h:694
+ Here is the caller graph for this function:

◆ cbeginSafe()

template<typename Key , typename Val , typename Alloc >
INLINE HashTable< Key, Val, Alloc >::const_iterator_safe gum::HashTable< Key, Val, Alloc >::cbeginSafe ( ) const

Returns the safe const_iterator pointing to the beginning of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe const_iterator pointing to the beginning of the hashtable.

Definition at line 715 of file hashTable_tpl.h.

Referenced by gum::LeastSquareTestPolicy< GUM_SCALAR >::add(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrABeginSafe(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrBBeginSafe(), gum::SetTerminalNodePolicy< GUM_SCALAR >::beginValues(), and gum::IMDDI< AttributeSelection, isScalar >::rebuildFunctionGraph__().

715  {
716  // if the table is empty, make the begin and end point to the same element
717  if (nb_elements__ == Size(0))
718  return const_iterator_safe{cendSafe()};
719  else
720  return const_iterator_safe{*this};
721  }
HashTableConstIteratorSafe< Key, Val > const_iterator_safe
Types for STL compliance.
Definition: hashTable.h:696
const const_iterator_safe & cendSafe() const noexcept
Returns the safe const_iterator pointing to the end of the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ cend()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator & gum::HashTable< Key, Val, Alloc >::cend ( ) const
noexcept

Returns the unsafe const_iterator pointing to the end of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns the unsafe const_iterator pointing to the end of the hashtable.

Definition at line 625 of file hashTable_tpl.h.

Referenced by gum::DAGCycleDetector::addArc(), gum::DAGCycleDetector::addWeightedSet__(), gum::BijectionImplementation< Idx, const std::string *, std::allocator< const std::string * >, std::is_scalar< Idx >::value &&std::is_scalar< const std::string * >::value >::copy__(), gum::DAGCycleDetector::delWeightedSet__(), gum::DAGCycleDetector::eraseArc(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator+(), gum::DAGCycleDetector::restrictWeightedSet__(), gum::learning::StructuralConstraintSliceOrder::StructuralConstraintSliceOrder(), and gum::credal::InferenceEngine< GUM_SCALAR >::updateCredalSets_().

625  {
626  // note that, here, we know for sure that HashTableIterEnd has been properly
627  // initialized as it is initialized by end4Statics, which is called by
628  // all hashtables' constructors
629  return *(reinterpret_cast< const const_iterator* >(
631  }
static const HashTableIterator< int, int > * HashTableIterEnd__
The unsafe iterator used by everyone.
Definition: hashTable.h:1834
HashTableConstIterator< Key, Val > const_iterator
Types for STL compliance.
Definition: hashTable.h:694
+ Here is the caller graph for this function:

◆ cendSafe()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator_safe & gum::HashTable< Key, Val, Alloc >::cendSafe ( ) const
noexcept

Returns the safe const_iterator pointing to the end of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe const_iterator pointing to the end of the hashtable.

Definition at line 685 of file hashTable_tpl.h.

Referenced by gum::LeastSquareTestPolicy< GUM_SCALAR >::add(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrAEndSafe(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrBEndSafe(), gum::SetTerminalNodePolicy< GUM_SCALAR >::hasValue(), gum::IMDDI< AttributeSelection, isScalar >::rebuildFunctionGraph__(), and gum::ITI< AttributeSelection, isScalar >::updateGraph().

685  {
686  // note that, here, we know for sure that HashTableIterEnd has been properly
687  // initialized as it is initialized by end4Statics, which is called by
688  // all hashtables' constructors
689  return *(reinterpret_cast< const const_iterator_safe* >(
691  }
HashTableConstIteratorSafe< Key, Val > const_iterator_safe
Types for STL compliance.
Definition: hashTable.h:696
static const HashTableIteratorSafe< int, int > * HashTableIterEndSafe__
The safe iterator used by everyone.
Definition: hashTable.h:1837
+ Here is the caller graph for this function:

◆ clear()

template<typename Key , typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::clear ( )

Removes all the elements in the hash table.

The function does not resize the nodes vector (even if the size of this one has been increased after the creation of the hash table) and it resets the iterators on the hash table to end. The method runs in linear time w.r.t. the number of iterators pointing to the hash table.

Definition at line 470 of file hashTable_tpl.h.

Referenced by gum::credal::CredalNet< GUM_SCALAR >::approximatedBinarization(), gum::Estimator< GUM_SCALAR >::clear(), gum::SetTerminalNodePolicy< GUM_SCALAR >::clearAllTerminalNodes(), gum::credal::InferenceEngine< GUM_SCALAR >::eraseAllEvidence(), gum::MultiDimSparse< GUM_SCALAR >::fill(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::credal::InferenceEngine< GUM_SCALAR >::initExpectations_(), gum::credal::InferenceEngine< GUM_SCALAR >::initMarginals_(), gum::credal::InferenceEngine< GUM_SCALAR >::initMarginalSets_(), gum::credal::MultipleInferenceEngine< GUM_SCALAR, BNInferenceEngine >::initThreadsData_(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidence(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidenceFile(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQuery(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQueryFile(), gum::credal::InferenceEngine< GUM_SCALAR >::repetitiveInit_(), and gum::Chi2::setConfidenceProba().

470  {
471  // update all the registered iterators: they should now point to nullptr
472  // and they are positioned to the end of the hashtable.
474 
475  // remove the buckets
476  for (Size i = Size(0); i < size__; ++i)
477  nodes__[i].clear();
478 
479  nb_elements__ = Size(0);
480  begin_index__ = std::numeric_limits< Size >::max();
481  }
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
void clearIterators__()
Clear all the safe iterators.
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
void clear()
Removes all the elements in the hash table.
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ clearIterators__()

template<typename Key , typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::clearIterators__ ( )
private

Clear all the safe iterators.

Definition at line 463 of file hashTable_tpl.h.

463  {
464  const Size len = safe_iterators__.size();
465  for (Size i = Size(0); i < len; ++i)
466  safe_iterators__[i]->clear();
467  }
std::vector< HashTableConstIteratorSafe< Key, Val > *> safe_iterators__
The list of safe iterators pointing to the hash table.
Definition: hashTable.h:1753
void clear()
Removes all the elements in the hash table.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ constEnd4Statics()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator & gum::HashTable< Key, Val, Alloc >::constEnd4Statics ( )
static

Returns the end iterator for other classes' statics (read the detailed description of this method).

To reduce memory consumption of hash tables (which are heavily used in aGrUM) while allowing fast for(iter=begin(); iter!=end();++iter) loops, end iterators are created just once as a static member of a non-template hashtable. While this scheme is efficient and it works quite effectively when manipulating hashtables, it has a drawback: other classes with static members using the HashTable's end() iterator may fail to work due to the well known "static initialization order fiasco" (see Marshall Cline's C++ FAQ for more details about this C++ feature). OK, so what is the problem? Consider for instance class Set. A Set contains a hashtable that stores all its elements in a convenient way. To reduce memory consumption, Set::end iterator is a static member that is initialized with a HashTable's end iterator. If the compiler decides to initialize Set::end before initializing HashTable::end, then Set::end will be in an incoherent state. Unfortunately, we cannot know for sure in which order static members will be initialized (the order is a compiler's decision). Hence, we shall enforce the fact that HashTable::end is initialized before Set::end. Using method HashTable::end4Statics will ensure this fact: it uses the C++ "construct on first use" idiom (see the C++ FAQ) that ensures that the order fiasco is avoided. More precisely, end4Statics initializes a global variable that is the very end iterator used by all hashtables. Now, this induces a small overhead. So, we also provide a HashTable::end() method that returns the end iterator without this small overhead, but assuming that function end4Statics has already been called once (which is always the case) when a hashtable has been created.

So, to summarize: when initializing static members, use constEnd4Statics() rather than cend(). In all the other cases, use simply the usual method cend().

Returns
Returns the end iterator for other classes' statics (read the detailed description of this method).

Definition at line 345 of file hashTable_tpl.h.

345  {
346  return *(reinterpret_cast< const const_iterator* >(
348  }
static const HashTableConstIterator< int, int > * constEnd4Statics()
Creates (if needed) and returns the iterator HashTableIterEnd__.
HashTableConstIterator< Key, Val > const_iterator
Types for STL compliance.
Definition: hashTable.h:694

◆ constEndSafe4Statics()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator_safe & gum::HashTable< Key, Val, Alloc >::constEndSafe4Statics ( )
static

Returns the end iterator for other classes' statics (read the detailed description of this method).

To reduce memory consumption of hash tables (which are heavily used in aGrUM) while allowing fast for(iter=begin(); iter!=end();++iter) loops, end iterators are created just once as a static member of a non-template hashtable. While this scheme is efficient and it works quite effectively when manipulating hashtables, it has a drawback: other classes with static members using the HashTable's end() iterator may fail to work due to the well known "static initialization order fiasco" (see Marshall Cline's C++ FAQ for more details about this C++ feature). OK, so what is the problem? Consider for instance class Set. A Set contains a hashtable that stores all its elements in a convenient way. To reduce memory consumption, Set::end iterator is a static member that is initialized with a HashTable's end iterator. If the compiler decides to initialize Set::end before initializing HashTable::end, then Set::end will be in an incoherent state. Unfortunately, we cannot know for sure in which order static members will be initialized (the order is a compiler's decision). Hence, we shall enforce the fact that HashTable::end is initialized before Set::end. Using method HashTable::end4Statics will ensure this fact: it uses the C++ "construct on first use" idiom (see the C++ FAQ) that ensures that the order fiasco is avoided. More precisely, end4Statics initializes a global variable that is the very end iterator used by all hashtables. Now, this induces a small overhead. So, we also provide a HashTable::end() method that returns the end iterator without this small overhead, but assuming that function end4Statics has already been called once (which is always the case) when a hashtable has been created.

So, to summarize: when initializing static members, use constEndSafe4Statics() rather than cendSafe(). In all the other cases, use simply the usual method cendSafe().

Returns
Returns the end iterator for other classes' statics (read the detailed description of this method).

Definition at line 359 of file hashTable_tpl.h.

359  {
360  return *(reinterpret_cast< const const_iterator_safe* >(
362  }
HashTableConstIteratorSafe< Key, Val > const_iterator_safe
Types for STL compliance.
Definition: hashTable.h:696
static const HashTableConstIteratorSafe< int, int > * constEndSafe4Statics()
Creates (if needed) and returns the iterator HashTableIterEndSafe__.

◆ copy__()

template<typename Key, typename Val, typename Alloc >
template<typename OtherAlloc >
void gum::HashTable< Key, Val, Alloc >::copy__ ( const HashTable< Key, Val, OtherAlloc > &  table)
private

A function used to perform copies of HashTables.

This code is shared by the copy constructor and the copy operator. The function ensures that when a memory allocation problem occurs:

  • no memory leak occurs
  • the hashtable returned is empty but in a coherent state
  • an exception is thrown

The function assumes that both this and table have arrays '__nodes' of the same size.

Parameters
tableThe gum::HashTable to copy.
Template Parameters
OtherAllocThe other gum::HashTable allocator.

Definition at line 310 of file hashTable_tpl.h.

311  {
312  // in debug mode, check that this and table have '__nodes' arrays of the
313  // same size
314  GUM_ASSERT(table.size__ == size__);
315 
316  // try to fill the array of chained lists
317  for (Size i = 0; i < table.size__; ++i) {
318  try {
319  nodes__[i] = table.nodes__[i];
320  } catch (...) {
321  // here we could allocate the nodes__[j], j=0..i-1, so we should
322  // deallocate them
323  for (Size j = 0; j < size__; ++j)
324  nodes__[j].clear();
325 
326  nb_elements__ = Size(0);
327 
328  // propagate the exception
329  throw;
330  }
331  }
332 
333  nb_elements__ = table.nb_elements__;
334  }
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
void clear()
Removes all the elements in the hash table.
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ create__()

template<typename Key , typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::create__ ( Size  size)
private

Used by all default constructors (general and specialized).

Parameters
sizeThe size of the gum::HashTable to create.

Definition at line 365 of file hashTable_tpl.h.

365  {
366  // setup the nodes__ vector (contains only empty lists)
367  nodes__.resize(size);
368 
369  for (auto& list: nodes__) {
370  list.setAllocator(alloc__);
371  }
372 
373  // set up properly the hash function
374  hash_func__.resize(size);
375 
376  // make sure the end() iterator is constructed properly
377  end4Statics();
378  endSafe4Statics();
379  }
static const iterator_safe & endSafe4Statics()
Returns the end iterator for other classes&#39; statics (read the detailed description of this method)...
Size size() const noexcept
Returns the number of elements stored into the hashtable.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
static const iterator & end4Statics()
Returns the end iterator for other classes&#39; statics (read the detailed description of this method)...

◆ emplace() [1/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename... Args>
INLINE HashTable< Key, Val, Alloc >::value_type& gum::HashTable< Key, Val, Alloc >::emplace ( Args &&...  args)

Definition at line 941 of file hashTable_tpl.h.

941  {
942  Bucket* bucket = alloc__.allocate(1);
943 
944  try {
945  alloc__.construct(bucket,
947  std::forward< Args >(args)...);
948  } catch (...) {
949  alloc__.deallocate(bucket, 1);
950  throw;
951  }
952 
953  insert__(bucket);
954  return bucket->elt();
955  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
void insert__(Bucket *bucket)
Adds a new element (actually a copy of this element) in the hash table.

◆ emplace() [2/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename... Args>
value_type& gum::HashTable< Key, Val, Alloc >::emplace ( Args &&...  args)

Emplace a new element into the hashTable.

If there already exists an element with the same key in the list and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Returns
a reference to the pair (key,val) inserted in the hash table.
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.
Parameters
argsThe element to emplace.

◆ empty()

template<typename Key , typename Val , typename Alloc >
INLINE bool gum::HashTable< Key, Val, Alloc >::empty ( ) const
noexcept

Indicates whether the hash table is empty.

Returns
Returns true if the gum::HashTable is empty.

Definition at line 1085 of file hashTable_tpl.h.

Referenced by gum::prm::PRMFactory< GUM_SCALAR >::addInstance(), gum::credal::InferenceEngine< GUM_SCALAR >::dynamicExpectations_(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidence(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidenceFile(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQuery(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQueryFile(), gum::MultiDimFunctionGraphProjector< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::project(), gum::BayesBall::relevantPotentials(), and gum::credal::InferenceEngine< GUM_SCALAR >::toString().

1085  {
1086  return (nb_elements__ == Size(0));
1087  }
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ end() [1/2]

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::iterator & gum::HashTable< Key, Val, Alloc >::end ( )
noexcept

Returns the unsafe iterator pointing to the end of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns the unsafe iterator pointing to the end of the hashtable.

Definition at line 605 of file hashTable_tpl.h.

Referenced by gum::Estimator< GUM_SCALAR >::confidence(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::learning::Miic::orientation_3off2_(), gum::learning::Miic::orientation_miic_(), and gum::SmallObjectAllocator::~SmallObjectAllocator().

605  {
606  // note that, here, we know for sure that HashTableIterEnd has been properly
607  // initialized as it is initialized by end4Statics, which is called by
608  // all hashtables' constructors
609  return *(reinterpret_cast< const iterator* >(
611  }
static const HashTableIterator< int, int > * HashTableIterEnd__
The unsafe iterator used by everyone.
Definition: hashTable.h:1834
HashTableIterator< Key, Val > iterator
Types for STL compliance.
Definition: hashTable.h:693
+ Here is the caller graph for this function:

◆ end() [2/2]

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator & gum::HashTable< Key, Val, Alloc >::end ( ) const
noexcept

Returns the unsafe const_iterator pointing to the end of the hashtable.

Unsafe iterators are slightly faster than safe iterators. However, BE CAREFUL when using them: they should ONLY be used when you have the guarantee that they will never point to a deleted element. If unsure, prefer using the safe iterators (those are only slightly slower).

Returns
Returns the unsafe const_iterator pointing to the end of the hashtable.

Definition at line 615 of file hashTable_tpl.h.

615  {
616  // note that, here, we know for sure that HashTableIterEnd has been properly
617  // initialized as it is initialized by end4Statics, which is called by
618  // all hashtables' constructors
619  return *(reinterpret_cast< const const_iterator* >(
621  }
static const HashTableIterator< int, int > * HashTableIterEnd__
The unsafe iterator used by everyone.
Definition: hashTable.h:1834
HashTableConstIterator< Key, Val > const_iterator
Types for STL compliance.
Definition: hashTable.h:694

◆ end4Statics()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::iterator & gum::HashTable< Key, Val, Alloc >::end4Statics ( )
static

Returns the end iterator for other classes' statics (read the detailed description of this method).

To reduce memory consumption of hash tables (which are heavily used in aGrUM) while allowing fast for(iter=begin(); iter!=end();++iter) loops, end iterators are created just once as a static member of a non-template hashtable. While this scheme is efficient and it works quite effectively when manipulating hashtables, it has a drawback: other classes with static members using the HashTable's end() iterator may fail to work due to the well known "static initialization order fiasco" (see Marshall Cline's C++ FAQ for more details about this C++ feature). OK, so what is the problem? Consider for instance class Set. A Set contains a hashtable that stores all its elements in a convenient way. To reduce memory consumption, Set::end iterator is a static member that is initialized with a HashTable's end iterator. If the compiler decides to initialize Set::end before initializing HashTable::end, then Set::end will be in an incoherent state. Unfortunately, we cannot know for sure in which order static members will be initialized (the order is a compiler's decision). Hence, we shall enforce the fact that HashTable::end is initialized before Set::end. Using method HashTable::end4Statics will ensure this fact: it uses the C++ "construct on first use" idiom (see the C++ FAQ) that ensures that the order fiasco is avoided. More precisely, end4Statics initializes a global variable that is the very end iterator used by all hashtables. Now, this induces a small overhead. So, we also provide a HashTable::end() method that returns the end iterator without this small overhead, but assuming that function end4Statics has already been called once (which is always the case) when a hashtable has been created.

So, to summarize: when initializing static members, use end4Statics() rather than end(). In all the other cases, use simply the usual method end().

Returns
Returns the end iterator for other classes' statics (read the detailed description of this method).

Definition at line 338 of file hashTable_tpl.h.

338  {
339  return *(reinterpret_cast< const iterator* >(
341  }
static const HashTableIterator< int, int > * end4Statics()
Creates (if needed) and returns the iterator HashTableIterEnd__.
HashTableIterator< Key, Val > iterator
Types for STL compliance.
Definition: hashTable.h:693

◆ endSafe() [1/2]

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::iterator_safe & gum::HashTable< Key, Val, Alloc >::endSafe ( )
noexcept

Returns the safe iterator pointing to the end of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe iterator pointing to the end of the hashtable.

Definition at line 665 of file hashTable_tpl.h.

Referenced by gum::SetTerminalNodePolicy< GUM_SCALAR >::clearAllTerminalNodes(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::LeafAggregator::leavesMap(), gum::StructuredPlaner< double >::optimalPolicy2String(), gum::SetTerminalNodePolicy< GUM_SCALAR >::terminalNodeId(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::toDot(), gum::ITI< AttributeSelection, isScalar >::updateGraph(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::~IncrementalGraphLearner(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::~MultiDimFunctionGraphOperator(), and gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::~Regress().

665  {
666  // note that, here, we know for sure that HashTableIterEnd has been properly
667  // initialized as it is initialized by end4Statics, which is called by
668  // all hashtables' constructors
669  return *(reinterpret_cast< const iterator_safe* >(
671  }
HashTableIteratorSafe< Key, Val > iterator_safe
Types for STL compliance.
Definition: hashTable.h:695
static const HashTableIteratorSafe< int, int > * HashTableIterEndSafe__
The safe iterator used by everyone.
Definition: hashTable.h:1837
+ Here is the caller graph for this function:

◆ endSafe() [2/2]

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::const_iterator_safe & gum::HashTable< Key, Val, Alloc >::endSafe ( ) const
noexcept

Returns the safe const_iterator pointing to the end of the hashtable.

Safe iterators are slightly slower than unsafe ones but they guarantee that you will never get a segfault if they try to access to a deleted element or if they try a ++ operation from a deleted element.

Returns
Returns the safe const_iterator pointing to the end of the hashtable.

Definition at line 675 of file hashTable_tpl.h.

675  {
676  // note that, here, we know for sure that HashTableIterEnd has been properly
677  // initialized as it is initialized by end4Statics, which is called by
678  // all hashtables' constructors
679  return *(reinterpret_cast< const const_iterator_safe* >(
681  }
HashTableConstIteratorSafe< Key, Val > const_iterator_safe
Types for STL compliance.
Definition: hashTable.h:696
static const HashTableIteratorSafe< int, int > * HashTableIterEndSafe__
The safe iterator used by everyone.
Definition: hashTable.h:1837

◆ endSafe4Statics()

template<typename Key , typename Val , typename Alloc >
INLINE const HashTable< Key, Val, Alloc >::iterator_safe & gum::HashTable< Key, Val, Alloc >::endSafe4Statics ( )
static

Returns the end iterator for other classes' statics (read the detailed description of this method).

To reduce memory consumption of hash tables (which are heavily used in aGrUM) while allowing fast for(iter=begin(); iter!=end();++iter) loops, end iterators are created just once as a static member of a non-template hashtable. While this scheme is efficient and it works quite effectively when manipulating hashtables, it has a drawback: other classes with static members using the HashTable's end() iterator may fail to work due to the well known "static initialization order fiasco" (see Marshall Cline's C++ FAQ for more details about this C++ feature). OK, so what is the problem? Consider for instance class Set. A Set contains a hashtable that stores all its elements in a convenient way. To reduce memory consumption, Set::end iterator is a static member that is initialized with a HashTable's end iterator. If the compiler decides to initialize Set::end before initializing HashTable::end, then Set::end will be in an incoherent state. Unfortunately, we cannot know for sure in which order static members will be initialized (the order is a compiler's decision). Hence, we shall enforce the fact that HashTable::end is initialized before Set::end. Using method HashTable::end4Statics will ensure this fact: it uses the C++ "construct on first use" idiom (see the C++ FAQ) that ensures that the order fiasco is avoided. More precisely, end4Statics initializes a global variable that is the very end iterator used by all hashtables. Now, this induces a small overhead. So, we also provide a HashTable::end() method that returns the end iterator without this small overhead, but assuming that function end4Statics has already been called once (which is always the case) when a hashtable has been created.

So, to summarize: when initializing static members, use endSafe4Statics() rather than endSafe(). In all the other cases, use simply the usual method endSafe().

Returns
Returns the end iterator for other classes' statics (read the detailed description of this method).

Definition at line 352 of file hashTable_tpl.h.

352  {
353  return *(reinterpret_cast< const iterator_safe* >(
355  }
static const HashTableIteratorSafe< int, int > * endSafe4Statics()
Creates (if needed) and returns the iterator HashTableIterEndSafe__.
HashTableIteratorSafe< Key, Val > iterator_safe
Types for STL compliance.
Definition: hashTable.h:695

◆ erase() [1/3]

template<typename Key, typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::erase ( const Key &  key)

Removes a given element from the hash table.

The element is the first one encountered in the list (from begin() to end()) having the specified key. If no such element can be found, nothing is done (in particular, it does not throw any exception). The function never resizes the nodes vector (even if the resizing policy would enable to decrease this size). The method runs in average in time linear to the number of iterators pointing to the table if the automatic resizing policy is set (else it is in linear time in the number of elements of the hash table plus the number of iterators).

Parameters
keyThe key of the element to remove.

Definition at line 1020 of file hashTable_tpl.h.

Referenced by gum::IncrementalGraphLearner< AttributeSelection, isScalar >::convertNode2Leaf_(), gum::DAGCycleDetector::delWeightedSet__(), gum::SetTerminalNodePolicy< GUM_SCALAR >::eraseTerminalNode(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::BayesBall::relevantPotentials(), gum::ITI< AttributeSelection, isScalar >::removeNode_(), and gum::IncrementalGraphLearner< AttributeSelection, isScalar >::removeNode_().

1020  {
1021  // get the hashed key
1022  Size hash = hash_func__(key);
1023 
1024  // get the bucket containing the element to erase
1025  HashTableBucket< Key, Val >* bucket = nodes__[hash].bucket(key);
1026 
1027  erase__(bucket, hash);
1028  }
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
void erase__(HashTableBucket< Key, Val > *bucket, Size index)
Erases a given bucket.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ erase() [2/3]

template<typename Key, typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::erase ( const iterator_safe iter)

Removes a given element from the hash table.

This method updates all the safe iterators pointing to the deleted element, i.e., when trying to dereference those iterators, an exception will be raised because they will know that the element they point to no longer exists.

Parameters
iterAn iterator over the element to remove.

Definition at line 1031 of file hashTable_tpl.h.

1031  {
1032  erase__(iter.getBucket__(), iter.getIndex__());
1033  }
void erase__(HashTableBucket< Key, Val > *bucket, Size index)
Erases a given bucket.

◆ erase() [3/3]

template<typename Key, typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::erase ( const const_iterator_safe iter)

Removes a given element from the hash table.

This method updates all the safe iterators pointing to the deleted element, i.e., when trying to dereference those iterators, an exception will be raised because they will know that the element they point to no longer exists.

Parameters
iterAn iterator over the element to remove.

Definition at line 1037 of file hashTable_tpl.h.

1037  {
1038  erase__(iter.getBucket__(), iter.getIndex__());
1039  }
void erase__(HashTableBucket< Key, Val > *bucket, Size index)
Erases a given bucket.

◆ erase__()

template<typename Key, typename Val, typename Alloc >
void gum::HashTable< Key, Val, Alloc >::erase__ ( HashTableBucket< Key, Val > *  bucket,
Size  index 
)
private

Erases a given bucket.

Definition at line 991 of file hashTable_tpl.h.

992  {
993  if (bucket == nullptr) return;
994 
995  // update the registered iterators pointing to this bucket
996  for (auto iter: safe_iterators__) {
997  if (iter->bucket__ == bucket) {
998  iter->operator++();
999  iter->next_bucket__ = iter->bucket__;
1000  iter->bucket__ = nullptr;
1001  } else if (iter->next_bucket__ == bucket) {
1002  iter->bucket__ = bucket;
1003  iter->operator++();
1004  iter->next_bucket__ = iter->bucket__;
1005  iter->bucket__ = nullptr;
1006  }
1007  }
1008 
1009  // remove the element from the nodes__ vector
1010  nodes__[index].erase(bucket);
1011 
1012  --nb_elements__;
1013 
1014  if ((index == begin_index__) && nodes__[index].empty()) {
1015  begin_index__ = std::numeric_limits< Size >::max();
1016  }
1017  }
std::vector< HashTableConstIteratorSafe< Key, Val > *> safe_iterators__
The list of safe iterators pointing to the hash table.
Definition: hashTable.h:1753
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
bool empty() const noexcept
Indicates whether the hash table is empty.

◆ eraseAllVal()

template<typename Key , typename Val, typename Alloc >
void gum::HashTable< Key, Val, Alloc >::eraseAllVal ( const Val &  val)

Removes all the elements having a certain value from the hash table.

If no such element can be found, nothing is done (in particular, it does not throw any exception). The function never resizes the nodes vector (even if the resizing policy would enable to decrease this size). Comparisons between Val instances are performed through == operators.

Parameters
valThe value to remove.

Definition at line 1076 of file hashTable_tpl.h.

1076  {
1077  for (auto iterAll = cbeginSafe(); iterAll != cendSafe(); ++iterAll) {
1078  if (iterAll.bucket__->val() == val) {
1079  erase__(iterAll.bucket__, iterAll.index__);
1080  }
1081  }
1082  }
const_iterator_safe cbeginSafe() const
Returns the safe const_iterator pointing to the beginning of the hashtable.
const const_iterator_safe & cendSafe() const noexcept
Returns the safe const_iterator pointing to the end of the hashtable.
void erase__(HashTableBucket< Key, Val > *bucket, Size index)
Erases a given bucket.

◆ eraseByVal()

template<typename Key , typename Val, typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::eraseByVal ( const Val &  val)

Removes a given element from the hash table.

The element is the first one encountered in the list (from begin() to end()) having the specified value. If no such element can be found, nothing is done (in particular, it does not throw any exception). The function never resizes the nodes vector (even if the resizing policy would enable to decrease this size). Comparisons between Val instances are performed through == operators. Logically, this method should have been named "erase", however, this would have prevented creating hash tables where both keys and vals have the same type. Hence we chose to add "ByVal" after erase to make a difference between erasing by key and erasing by val.

Parameters
valThe value to remove.

Definition at line 1042 of file hashTable_tpl.h.

1042  {
1043  for (auto iter = cbegin(); iter != cend(); ++iter)
1044  if (iter.bucket__->val() == val) {
1045  erase__(iter.getBucket__(), iter.getIndex__());
1046  return;
1047  }
1048  }
const const_iterator & cend() const noexcept
Returns the unsafe const_iterator pointing to the end of the hashtable.
void erase__(HashTableBucket< Key, Val > *bucket, Size index)
Erases a given bucket.
const_iterator cbegin() const
Returns an unsafe const_iterator pointing to the beginning of the hashtable.

◆ exists()

template<typename Key, typename Val , typename Alloc >
INLINE bool gum::HashTable< Key, Val, Alloc >::exists ( const Key &  key) const

Checks whether there exists an element with a given key in the hashtable.

The method runs in average in constant time if the resizing policy is set.

Parameters
keyThe key to test for existence.
Returns
True if key is in this gum::HashTable.

Definition at line 745 of file hashTable_tpl.h.

Referenced by gum::prm::PRMInference< double >::addEvidence(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::addObservation(), gum::SetTerminalNodePolicy< GUM_SCALAR >::addTerminalNode(), gum::DAGCycleDetector::addWeightedSet__(), gum::SmallObjectAllocator::allocate(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrAMarginal(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrBMarginal(), gum::BayesNetFactory< GUM_SCALAR >::BayesNetFactory(), gum::prm::o3prm::O3ClassFactory< GUM_SCALAR >::checkImplementation__(), gum::BayesNetFactory< GUM_SCALAR >::checkVariableName__(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::compute__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::compute__(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::copyAndMultiplyByScalar(), gum::DAGCycleDetector::delWeightedSet__(), gum::ArcGraphPart::directedPath(), gum::ArcGraphPart::directedUnorientedPath(), gum::SetTerminalNodePolicy< GUM_SCALAR >::eraseTerminalNode(), gum::HashTable< Val, Size, IndexAllocator >::exists(), gum::learning::Miic::existsDirectedPath__(), gum::SetTerminalNodePolicy< GUM_SCALAR >::existsTerminalNodeWithId(), gum::prm::StructuredBayesBall< GUM_SCALAR >::fromChild__(), gum::prm::StructuredBayesBall< GUM_SCALAR >::fromParent__(), gum::MultiDimSparse< GUM_SCALAR >::get(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::isTerminal(), gum::ContingencyTable< Idx, GUM_SCALAR >::joint(), gum::prm::gspan::InterfaceGraph< GUM_SCALAR >::label__(), gum::LeafAggregator::leavesMap(), gum::MixedGraph::mixedOrientedPath(), gum::MixedGraph::mixedUnorientedPath(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*=(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator+(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator-(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator==(), gum::StructuredPlaner< double >::optimalPolicy2String(), gum::learning::Miic::orientation_3off2_(), gum::Estimator< GUM_SCALAR >::posterior(), gum::learning::Miic::propagatesHead_(), gum::IMDDI< AttributeSelection, isScalar >::rebuildFunctionGraph__(), gum::StructuredPlaner< double >::recurArgMaxCopy__(), gum::StructuredPlaner< double >::recurExtractOptPol__(), gum::BayesBall::relevantPotentials(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::removeNode_(), gum::Potential< GUM_SCALAR >::reorganize(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClass(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClassElement(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveInterface(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveSlotType(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveType(), gum::prm::PRMFactory< GUM_SCALAR >::retrieveCommonType__(), gum::Estimator< GUM_SCALAR >::setFromBN(), gum::EliminationSequenceStrategy::setGraph(), gum::credal::CredalNet< GUM_SCALAR >::sort_varType__(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::toDot(), gum::credal::InferenceEngine< GUM_SCALAR >::toString(), gum::EdgeGraphPart::undirectedPath(), gum::Estimator< GUM_SCALAR >::update(), and gum::BayesNetFactory< GUM_SCALAR >::variableName().

745  {
746  return nodes__[hash_func__(key)].exists(key);
747  }
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727

◆ getWithDefault() [1/2]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::mapped_type & gum::HashTable< Key, Val, Alloc >::getWithDefault ( const Key &  key,
const Val &  default_value 
)

Returns a reference on the element the key of which is passed in argument.

In case of multiple identical keys in the hash table, the first value encountered is returned. The method runs in constant time. In case of not found key, (key,default_value) is inserted in *this.

Parameters
keyThe key for wich we want the value.
default_valueThe default value to return if key does not match any value.
Returns
Returns a reference on the element the key of which is passed in argument.

Definition at line 959 of file hashTable_tpl.h.

960  {
961  Bucket* bucket = nodes__[hash_func__(key)].bucket(key);
962 
963  if (bucket == nullptr)
964  return insert(key, default_value).second;
965  else
966  return bucket->val();
967  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.

◆ getWithDefault() [2/2]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::mapped_type & gum::HashTable< Key, Val, Alloc >::getWithDefault ( Key &&  key,
Val &&  default_value 
)

Returns a reference on the element the key of which is passed in argument.

In case of multiple identical keys in the hash table, the first value encountered is returned. The method runs in constant time. In case of not found key, (key,default_value) is inserted in *this.

Parameters
keyThe key for wich we want the value.
default_valueThe default value to return if key does not match any value.
Returns
Returns a reference on the element the key of which is passed in argument.

Definition at line 971 of file hashTable_tpl.h.

971  {
972  Bucket* bucket = nodes__[hash_func__(key)].bucket(key);
973 
974  if (bucket == nullptr)
975  return insert(std::move(key), std::move(default_value)).second;
976  else
977  return bucket->val();
978  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.

◆ insert() [1/4]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::value_type & gum::HashTable< Key, Val, Alloc >::insert ( const Key &  key,
const Val &  val 
)

Adds a new element (actually a copy of this element) into the hash table.

If there already exists an element with the same key in the table and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Returns
As only a copy of val is inserted into the hashtable, the method returns a reference on a copy of the pair (key,val).
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.
Parameters
keyThe key to add.
valThe value to add.
Returns
The value added by copy to this gum::HashTable.

Definition at line 876 of file hashTable_tpl.h.

Referenced by gum::DAGCycleDetector::addArc(), gum::prm::SVE< GUM_SCALAR >::addDelayedVariable__(), gum::prm::PRMInference< double >::addEvidence(), gum::prm::PRMFactory< GUM_SCALAR >::addInstance(), gum::prm::o3prm::O3SystemFactory< GUM_SCALAR >::addInstances__(), gum::prm::o3prm::O3InterfaceFactory< GUM_SCALAR >::addInterface2Dag__(), gum::prm::ClassDependencyGraph< GUM_SCALAR >::addNode__(), gum::prm::gspan::DFSTree< GUM_SCALAR >::addRoot(), gum::SetTerminalNodePolicy< GUM_SCALAR >::addTerminalNode(), gum::prm::o3prm::O3TypeFactory< GUM_SCALAR >::addTypes2Dag__(), gum::DAGCycleDetector::addWeightedSet__(), gum::BarrenNodesFinder::barrenNodes(), gum::BarrenNodesFinder::barrenPotentials(), gum::BayesNetFactory< GUM_SCALAR >::BayesNetFactory(), gum::prm::o3prm::O3ClassFactory< GUM_SCALAR >::checkAndAddNodesToDag__(), gum::MaxInducedWidthMCBayesNetGenerator< GUM_SCALAR, ICPTGenerator, ICPTDisturber >::checkConditions__(), gum::prm::ClassDependencyGraph< GUM_SCALAR >::ClassDependencyGraph(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::compute__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::compute__(), gum::DefaultJunctionTreeStrategy::computeJunctionTree__(), gum::ExactBNdistance< GUM_SCALAR >::computeKL_(), gum::GibbsBNdistance< GUM_SCALAR >::computeKL_(), gum::StaticTriangulation::computeMaxPrimeJunctionTree__(), gum::StaticTriangulation::computeRecursiveThinning__(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::copyAndMultiplyByScalar(), gum::Chi2::criticalValue(), gum::learning::genericBNLearner::Database::Database(), gum::ArcGraphPart::directedPath(), gum::ArcGraphPart::directedUnorientedPath(), gum::BayesNetFactory< GUM_SCALAR >::endVariableDeclaration(), gum::DAGCycleDetector::eraseArc(), gum::Estimator< GUM_SCALAR >::Estimator(), gum::learning::Miic::existsDirectedPath__(), gum::prm::PRMFormAttribute< GUM_SCALAR >::fillCpf__(), gum::prm::StructuredBayesBall< GUM_SCALAR >::fillMaps__(), gum::Regress< GUM_SCALAR, COMBINEOPERATOR, PROJECTOPERATOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::MultiDimFunctionGraphOperator< GUM_SCALAR, FUNCTOR, TerminalNodePolicy >::findRetrogradeVariables__(), gum::prm::StructuredBayesBall< GUM_SCALAR >::fromChild__(), gum::prm::StructuredBayesBall< GUM_SCALAR >::fromParent__(), gum::MultiDimFunctionGraphGenerator::generate(), gum::SimpleBayesNetGenerator< GUM_SCALAR, ICPTGenerator >::generateBN(), gum::DAGCycleDetector::hasCycleFromModifications(), gum::credal::InferenceEngine< GUM_SCALAR >::initExpectations_(), gum::AdaptiveRMaxPlaner::initialize(), gum::credal::InferenceEngine< GUM_SCALAR >::initMarginals_(), gum::credal::InferenceEngine< GUM_SCALAR >::initMarginalSets_(), gum::PriorityQueueImplementation< NodeId, double, std::greater< double >, std::allocator< NodeId >, std::is_scalar< NodeId >::value >::insert(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidence(), gum::credal::InferenceEngine< GUM_SCALAR >::insertEvidenceFile(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::insertInternalNode_(), gum::ITI< AttributeSelection, isScalar >::insertNode_(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQuery(), gum::credal::InferenceEngine< GUM_SCALAR >::insertQueryFile(), gum::ITI< AttributeSelection, isScalar >::ITI(), gum::prm::gspan::InterfaceGraph< GUM_SCALAR >::label__(), gum::LeafAggregator::leavesMap(), gum::HashTable< Val, Size, IndexAllocator >::map(), gum::MultiDimFunctionGraphManager< bool, ExactTerminalNodePolicy >::minimizeSize(), gum::MixedGraph::mixedOrientedPath(), gum::MixedGraph::mixedUnorientedPath(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator+(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator-(), gum::PriorityQueueImplementation< NodeId, double, std::greater< double >, std::allocator< NodeId >, std::is_scalar< NodeId >::value >::operator=(), gum::StructuredPlaner< double >::optimalPolicy2String(), gum::prm::gspan::Pattern::Pattern(), gum::learning::genericBNLearner::prepare_miic_3off2__(), gum::IMDDI< AttributeSelection, isScalar >::rebuildFunctionGraph__(), gum::StructuredPlaner< double >::recurArgMaxCopy__(), gum::StructuredPlaner< double >::recurExtractOptPol__(), gum::BayesBall::relevantPotentials(), gum::Potential< GUM_SCALAR >::reorganize(), gum::credal::InferenceEngine< GUM_SCALAR >::repetitiveInit_(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClass(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClassElement(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveInterface(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveSlotType(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveType(), gum::DAGCycleDetector::restrictWeightedSet__(), gum::prm::PRMFactory< GUM_SCALAR >::retrieveCommonType__(), gum::prm::PRMClass< double >::scope(), gum::DAGCycleDetector::setDAG(), gum::Estimator< GUM_SCALAR >::setFromBN(), gum::Estimator< GUM_SCALAR >::setFromLBP(), gum::GraphicalModel::setProperty(), gum::learning::genericBNLearner::setSliceOrder(), gum::BayesNetFactory< GUM_SCALAR >::setVariable(), gum::credal::CredalNet< GUM_SCALAR >::sort_varType__(), gum::prm::GSpan< GUM_SCALAR >::subgraph_mining__(), gum::TaxiSimulator::TaxiSimulator(), gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::toDot(), gum::IncrementalGraphLearner< AttributeSelection, isScalar >::transpose_(), gum::EdgeGraphPart::undirectedPath(), and gum::ITI< AttributeSelection, isScalar >::updateGraph().

876  {
877  Bucket* bucket = alloc__.allocate(1);
878 
879  try {
880  alloc__.construct(bucket, thekey, theval);
881  } catch (...) {
882  alloc__.deallocate(bucket, 1);
883  throw;
884  }
885 
886  insert__(bucket);
887  return bucket->elt();
888  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
void insert__(Bucket *bucket)
Adds a new element (actually a copy of this element) in the hash table.

◆ insert() [2/4]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::value_type & gum::HashTable< Key, Val, Alloc >::insert ( Key &&  key,
Val &&  val 
)

Moves a new element in the hash table.

If there already exists an element with the same key in the table and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Returns
a reference to the pair (key,val) in the hashtable.
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.
Parameters
keyThe key to move.
valThe value to move.
Returns
The value moved to this gum::HashTable.

Definition at line 892 of file hashTable_tpl.h.

892  {
893  Bucket* bucket = alloc__.allocate(1);
894 
895  try {
896  alloc__.construct(bucket, std::move(thekey), std::move(theval));
897  } catch (...) {
898  alloc__.deallocate(bucket, 1);
899  throw;
900  }
901 
902  insert__(bucket);
903  return bucket->elt();
904  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
void insert__(Bucket *bucket)
Adds a new element (actually a copy of this element) in the hash table.

◆ insert() [3/4]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::value_type & gum::HashTable< Key, Val, Alloc >::insert ( const std::pair< Key, Val > &  elt)

Adds a new element (actually a copy of this element) into the hash table.

If there already exists an element with the same key in the table and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Returns
As only a copy of val is inserted into the hashtable, the method returns a reference on a copy of the pair (key,val).
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.
Parameters
eltThe pair of key value to add.
Returns
The value added by copy to this gum::HashTable.

Definition at line 908 of file hashTable_tpl.h.

908  {
909  Bucket* bucket = alloc__.allocate(1);
910 
911  try {
912  alloc__.construct(bucket, reinterpret_cast< const value_type& >(elt));
913  } catch (...) {
914  alloc__.deallocate(bucket, 1);
915  throw;
916  }
917 
918  insert__(bucket);
919  return bucket->elt();
920  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
void insert__(Bucket *bucket)
Adds a new element (actually a copy of this element) in the hash table.

◆ insert() [4/4]

template<typename Key, typename Val, typename Alloc >
INLINE HashTable< Key, Val, Alloc >::value_type & gum::HashTable< Key, Val, Alloc >::insert ( std::pair< Key, Val > &&  elt)

Moves a new element in the hash table.

If there already exists an element with the same key in the table and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Returns
a reference to the pair (key,val) in the hashtable.
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.
Parameters
eltThe pair of key value to move in this gum::HashTable.
Returns
The value moved to this gum::HashTable.

Definition at line 924 of file hashTable_tpl.h.

924  {
925  Bucket* bucket = alloc__.allocate(1);
926 
927  try {
928  alloc__.construct(bucket, std::move(reinterpret_cast< value_type& >(elt)));
929  } catch (...) {
930  alloc__.deallocate(bucket, 1);
931  throw;
932  }
933 
934  insert__(bucket);
935  return bucket->elt();
936  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
void insert__(Bucket *bucket)
Adds a new element (actually a copy of this element) in the hash table.

◆ insert__()

template<typename Key , typename Val , typename Alloc >
void gum::HashTable< Key, Val, Alloc >::insert__ ( Bucket bucket)
private

Adds a new element (actually a copy of this element) in the hash table.

If there already exists an element with the same key in the list and the uniqueness policy prevents multiple identical keys to belong to the same hashtable, an exception DuplicateElement is thrown. If the uniqueness policy is not set, the method runs in the worst case in constant time, else if the automatic resizing policy is set, it runs in constant time in average linear in the number of elements by slot.

Parameters
bucketThe bucket inserted in the hash table.
Exceptions
DuplicateElementis thrown when attempting to insert a pair (key,val) in a hash table containing already a pair with the same key and when the hash table's uniqueness policy is set.

Definition at line 840 of file hashTable_tpl.h.

840  {
841  Size hash_key = hash_func__(bucket->key());
842 
843  // check that there does not already exist an element with the same key
844  if (key_uniqueness_policy__ && nodes__[hash_key].exists(bucket->key())) {
845  // remove the bucket from memory
846  Key k = bucket->key();
847  alloc__.destroy(bucket);
848  alloc__.deallocate(bucket, 1);
849  GUM_ERROR(DuplicateElement,
850  "the hashtable contains an element with the same key (" << k
851  << ")");
852  }
853 
854  // check whether there is sufficient space to insert the new pair
855  // if not, resize the current hashtable
856  if (resize_policy__
858  resize(size__ << 1);
859  hash_key = hash_func__(bucket->key());
860  }
861 
862  // add the new pair
863  nodes__[hash_key].insert(bucket);
864  ++nb_elements__;
865 
866  // recompute the index of the beginning of the hashtable if possible
867  // WARNING: if begin_index__ = std::numeric_limits<Size>::max (), we CANNOT
868  // recompute the index because we cannot know whether the current index is
869  // equal to max because there was no element in the hashtable or whether a
870  // previous erase__() has set the index to max.
871  if (begin_index__ < hash_key) { begin_index__ = hash_key; }
872  }
void resize(Size new_size)
Changes the number of slots in the &#39;nodes&#39; vector of the hash table.
static constexpr Size default_mean_val_by_slot
The average number of elements admissible by slots.
Definition: hashTable.h:87
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
#define GUM_ERROR(type, msg)
Definition: exceptions.h:55

◆ key()

template<typename Key, typename Val , typename Alloc >
INLINE const Key & gum::HashTable< Key, Val, Alloc >::key ( const Key &  key) const

Returns a reference on a given key.

Some complex structures use pointers on keys of hashtables. These structures thus require that we do not only get a copy of a given key, but the key stored in the hashtable itself. This is the very purpose of this function.

Parameters
keyThe key to return.
Returns
Returns a reference on a given key.
Exceptions
NotFoundRaised if the element cannot be found.

Definition at line 1064 of file hashTable_tpl.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::keyByVal(), gum::StructuredPlaner< double >::optimalPolicy2String(), and gum::MultiDimFunctionGraph< bool, ExactTerminalNodePolicy >::toDot().

1064  {
1065  // get the bucket corresponding to the key
1066  Bucket* bucket = nodes__[hash_func__(key)].bucket(key);
1067 
1068  if (bucket == nullptr) {
1069  GUM_ERROR(NotFound, "key does not belong to the hashtable");
1070  }
1071 
1072  return bucket->key();
1073  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
#define GUM_ERROR(type, msg)
Definition: exceptions.h:55
+ Here is the caller graph for this function:

◆ keyByVal()

template<typename Key , typename Val, typename Alloc >
INLINE const Key & gum::HashTable< Key, Val, Alloc >::keyByVal ( const Val &  val) const

Returns a reference on the key given a value.

In case of multiple identical values in the hash table, the first key encountered is returned. The method runs in linear time.

Parameters
valThe value for which the key is returned.
Returns
Returns a reference on the key given a value.
Exceptions
NotFoundRaised if the element cannot be found.

Definition at line 1056 of file hashTable_tpl.h.

1056  {
1057  for (auto iter = begin(); iter != end(); ++iter)
1058  if (iter.bucket__->val() == val) return iter.key();
1059 
1060  GUM_ERROR(NotFound, "not enough elements in the chained list");
1061  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
#define GUM_ERROR(type, msg)
Definition: exceptions.h:55

◆ keyUniquenessPolicy()

template<typename Key , typename Val , typename Alloc >
INLINE bool gum::HashTable< Key, Val, Alloc >::keyUniquenessPolicy ( ) const
noexcept

Returns the current checking policy.

Returns
Returns the current checking policy.

Definition at line 767 of file hashTable_tpl.h.

767  {
769  }
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733

◆ map() [1/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(Val)  f,
Size  size,
bool  resize_pol,
bool  key_uniqueness_pol 
) const

Definition at line 1091 of file hashTable_tpl.h.

1092  {
1093  // determine the proper size of the hashtable
1094  // by default, the size of the table is set so that the table does not take
1095  // too much space while allowing to add a few elements without needing to
1096  // resize in autmatic resizing mode
1097  if (size == 0) size = std::max(Size(2), nb_elements__ / 2);
1098 
1099  // create a new table
1100  HashTable< Key, Mount, OtherAlloc > table(
1101  size, resize_pol, key_uniqueness_pol);
1102 
1103  // fill the new hash table
1104  for (auto iter = begin(); iter != end(); ++iter) {
1105  table.insert(iter.key(), f(iter.val()));
1106  }
1107 
1108  return table;
1109  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size size() const noexcept
Returns the number of elements stored into the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ map() [2/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(Val &)  f,
Size  size,
bool  resize_pol,
bool  key_uniqueness_pol 
) const

Definition at line 1113 of file hashTable_tpl.h.

1114  {
1115  // determine the proper size of the hashtable
1116  // by default, the size of the table is set so that the table does not take
1117  // too much space while allowing to add a few elements without needing to
1118  // resize in autmatic resizing mode
1119  if (size == Size(0)) size = std::max(Size(2), nb_elements__ / 2);
1120 
1121  // create a new table
1122  HashTable< Key, Mount, OtherAlloc > table(
1123  size, resize_pol, key_uniqueness_pol);
1124 
1125  // fill the new hash table
1126  for (auto iter = begin(); iter != end(); ++iter) {
1127  table.insert(iter.key(), f(const_cast< Val& >(iter.val())));
1128  }
1129 
1130  return table;
1131  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size size() const noexcept
Returns the number of elements stored into the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ map() [3/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(const Val &)  f,
Size  size,
bool  resize_pol,
bool  key_uniqueness_pol 
) const

Definition at line 1136 of file hashTable_tpl.h.

1139  {
1140  // determine the proper size of the hashtable
1141  // by default, the size of the table is set so that the table does not take
1142  // too much space while allowing to add a few elements without needing to
1143  // resize in autmatic resizing mode
1144  if (size == Size(0)) size = std::max(Size(2), nb_elements__ / 2);
1145 
1146  // create a new table
1147  HashTable< Key, Mount, OtherAlloc > table(
1148  size, resize_pol, key_uniqueness_pol);
1149 
1150  // fill the new hash table
1151  for (auto iter = begin(); iter != end(); ++iter) {
1152  table.insert(iter.key(), f(iter.val()));
1153  }
1154 
1155  return table;
1156  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size size() const noexcept
Returns the number of elements stored into the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ map() [4/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc >
HashTable< Key, Mount, OtherAlloc > INLINE gum::HashTable< Key, Val, Alloc >::map ( const Mount &  val,
Size  size,
bool  resize_pol,
bool  key_uniqueness_pol 
) const

Definition at line 1160 of file hashTable_tpl.h.

1161  {
1162  // determine the proper size of the hashtable
1163  // by default, the size of the table is set so that the table does not take
1164  // too much space while allowing to add a few elements without needing to
1165  // resize in autmatic resizing mode
1166  if (size == Size(0)) size = std::max(Size(2), nb_elements__ / 2);
1167 
1168  // create a new table
1169  HashTable< Key, Mount, OtherAlloc > table(
1170  size, resize_pol, key_uniqueness_pol);
1171 
1172  // fill the new hash table
1173  for (auto iter = begin(); iter != end(); ++iter) {
1174  table.insert(iter.key(), val);
1175  }
1176 
1177  return table;
1178  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size size() const noexcept
Returns the number of elements stored into the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ map() [5/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(Val)  f,
Size  size = Size(0),
bool  resize_pol = HashTableConst::default_resize_policy,
bool  key_uniqueness_pol = HashTableConst::default_uniqueness_policy 
) const

Transforms a hashtable of vals into a hashtable of mountains.

Warning
Although the resulting hashtable has the same number of elements as the original hashtable, by default, the size of the former may not be equal to that of the latter. Hence iterators on the original hashtable may not parse it in the same order as iterators on the resulting hashtable. To guarrantee that both hashtables have the same size (and thus have the elements in the same order), set the size argument to the size of the original hashtable.
Parameters
fA function that maps any Val element into a Mount.
sizeThe size of the resulting hashtable. When equal to 0, a default size is computed that is a good trade-off between space consumption and efficiency of new elements insertions
resize_polthe resizing policy (automatic or manual resizing)
key_uniqueness_poluniqueness policy
Returns
Returns the gum::HashTable of mountains.

◆ map() [6/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(Val &)  f,
Size  size = Size(0),
bool  resize_pol = HashTableConst::default_resize_policy,
bool  key_uniqueness_pol = HashTableConst::default_uniqueness_policy 
) const

Transforms a hashtable of vals into a hashtable of mountains.

Warning
Although the resulting hashtable has the same number of elements as the original hashtable, by default, the size of the former may not be equal to that of the latter. Hence iterators on the original hashtable may not parse it in the same order as iterators on the resulting hashtable. To guarrantee that both hashtables have the same size (and thus have the elements in the same order), set the size argument to the size of the original hashtable.
Parameters
fA function that maps any Val element into a Mount.
sizeThe size of the resulting hashtable. When equal to 0, a default size is computed that is a good trade-off between space consumption and efficiency of new elements insertions
resize_polthe resizing policy (automatic or manual resizing)
key_uniqueness_poluniqueness policy
Returns
Returns the gum::HashTable of mountains.

◆ map() [7/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > gum::HashTable< Key, Val, Alloc >::map ( Mount(*)(const Val &)  f,
Size  size = Size(0),
bool  resize_pol = HashTableConst::default_resize_policy,
bool  key_uniqueness_pol = HashTableConst::default_uniqueness_policy 
) const

Transforms a hashtable of vals into a hashtable of mountains.

Warning
Although the resulting hashtable has the same number of elements as the original hashtable, by default, the size of the former may not be equal to that of the latter. Hence iterators on the original hashtable may not parse it in the same order as iterators on the resulting hashtable. To guarrantee that both hashtables have the same size (and thus have the elements in the same order), set the size argument to the size of the original hashtable.
Parameters
fA function that maps any Val element into a Mount.
sizeThe size of the resulting hashtable. When equal to 0, a default size is computed that is a good trade-off between space consumption and efficiency of new elements insertions
resize_polthe resizing policy (automatic or manual resizing)
key_uniqueness_poluniqueness policy
Returns
Returns the gum::HashTable of mountains.

◆ map() [8/8]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename Mount , typename OtherAlloc = typename Alloc::template rebind< std::pair< Key, Mount > >::other>
HashTable< Key, Mount, OtherAlloc > gum::HashTable< Key, Val, Alloc >::map ( const Mount &  val,
Size  size = Size(0),
bool  resize_pol = HashTableConst::default_resize_policy,
bool  key_uniqueness_pol = HashTableConst::default_uniqueness_policy 
) const

Creates a hashtable of mounts with a given value from a hashtable of vals.

Warning
Although the resulting hashtable has the same number of elements as the original hashtable, by default, the size of the former may not be equal to that of the latter. Hence iterators on the original hashtable may not parse it in the same order as iterators on the resulting hashtable. To guarrantee that both hashtables have the same size (and thus have the elements in the same order), set the size argument to the size of the original hashtable.
Parameters
valThe value taken by all the elements of the resulting hashtable.
sizeThe size of the resulting hashtable. When equal to 0, a default size is computed that is a good trade-off between space consumption and efficiency of new elements insertions
resize_polthe resizing policy (automatic or manual resizing)
key_uniqueness_poluniqueness policy
Returns
Returns the gum::HashTable of mountains.

◆ operator!=() [1/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename OtherAlloc >
bool gum::HashTable< Key, Val, Alloc >::operator!= ( const HashTable< Key, Val, OtherAlloc > &  from) const

Checks whether two hashtables contain different sets of elements.

Two hashtables are considered different if they contain different pairs (key,val). Two pairs are different if their keys have different hashed values, or if they are different in the sense of !=, or if their val's are different in the sense of !=.

Parameters
fromThe gum::HashTable to test for inequality.
Returns
True if this and from are not equal.

◆ operator!=() [2/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename OtherAlloc >
INLINE bool gum::HashTable< Key, Val, Alloc >::operator!= ( const HashTable< Key, Val, OtherAlloc > &  from) const

Definition at line 1199 of file hashTable_tpl.h.

1200  {
1201  return !operator==(from);
1202  }
bool operator==(const HashTable< Key, Val, OtherAlloc > &from) const
Checks whether two hashtables contain the same elements.

◆ operator=() [1/3]

template<typename Key, typename Val, typename Alloc>
HashTable< Key, Val, Alloc > & gum::HashTable< Key, Val, Alloc >::operator= ( const HashTable< Key, Val, Alloc > &  from)

Copy operator.

The copy operators ensures that whenever a memory allocation problem occurs, no memory leak occurs as well and it also guarantees that in this case the hashtable returned is in a coherent state (it is an empty hashtable). Note that the copy not only involves copying pairs (key,value) but also the copy of the resize and key uniqueness policies.

Parameters
fromThe gum::HashTable to copy.
Returns
Returns this gum::HashTable.

Definition at line 494 of file hashTable_tpl.h.

495  {
496  // avoid self assignment
497  if (this != &from) {
498  // for debugging purposes
499  GUM_OP_CPY(HashTable);
500 
501  // first remove the current content of the hashtable and make
502  // the iterators point to end
503  clear();
504 
505  // if sizes of from's and this' nodes__ vectors are not the same,
506  // we need to remove the current nodes__' array and to create a
507  // new array with the correct size
508  if (size__ != from.size__) {
509  nodes__.resize(from.size__);
510 
511  for (Size i = Size(0); i < from.size__; ++i) {
512  nodes__[i].setAllocator(alloc__);
513  }
514 
515  size__ = from.size__;
516 
517  // update the hash function : this is important as the computation of
518  // the hash values heavily depends on the size of the hash table
519  hash_func__.resize(size__);
520  }
521 
522  resize_policy__ = from.resize_policy__;
523  key_uniqueness_policy__ = from.key_uniqueness_policy__;
524  begin_index__ = from.begin_index__;
525 
526  // perform the copy
527  copy__(from);
528  }
529 
530  return *this;
531  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
void copy__(const HashTable< Key, Val, OtherAlloc > &table)
A function used to perform copies of HashTables.
void clear()
Removes all the elements in the hash table.
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ operator=() [2/3]

template<typename Key, typename Val, typename Alloc >
template<typename OtherAlloc >
HashTable< Key, Val, Alloc > & gum::HashTable< Key, Val, Alloc >::operator= ( const HashTable< Key, Val, OtherAlloc > &  from)

Generalized copy operator.

The copy operators ensures that whenever a memory allocation problem occurs, no memory leak occurs as well and it also guarantees that in this case the hashtable returned is in a coherent state (it is an empty hashtable). Note that the copy not only involves copying pairs (key,value) but also the copy of the resize and key uniqueness policies.

Parameters
fromThe gum::HashTable to copy.
Returns
Returns this gum::HashTable.

Definition at line 535 of file hashTable_tpl.h.

536  {
537  // avoid self assignment
538  if (this != reinterpret_cast< const HashTable< Key, Val, Alloc >* >(&from)) {
539  // for debugging purposes
540  GUM_OP_CPY(HashTable);
541 
542  // first remove the current content of the hashtable and make
543  // the iterators point to end
544  clear();
545 
546  // if sizes of from's and this' nodes__ vectors are not the same,
547  // we need to remove the current nodes__' array and to create a
548  // new array with the correct size
549  if (size__ != from.size__) {
550  nodes__.resize(from.size__);
551 
552  for (Size i = 0; i < from.size__; ++i) {
553  nodes__[i].setAllocator(alloc__);
554  }
555 
556  size__ = from.size__;
557 
558  // update the hash function : this is important as the computation of
559  // the hash values heavily depends on the size of the hash table
560  hash_func__.resize(size__);
561  }
562 
563  resize_policy__ = from.resize_policy__;
564  key_uniqueness_policy__ = from.key_uniqueness_policy__;
565  begin_index__ = from.begin_index__;
566 
567  // perform the copy
568  copy__(from);
569  }
570 
571  return *this;
572  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
void copy__(const HashTable< Key, Val, OtherAlloc > &table)
A function used to perform copies of HashTables.
void clear()
Removes all the elements in the hash table.
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ operator=() [3/3]

template<typename Key, typename Val, typename Alloc>
HashTable< Key, Val, Alloc > & gum::HashTable< Key, Val, Alloc >::operator= ( HashTable< Key, Val, Alloc > &&  from)

Move operator.

Parameters
fromThe gum::HashTable to move.
Returns
Returns this gum::HashTable.

Definition at line 575 of file hashTable_tpl.h.

576  {
577  // avoid self assignment
578  if (this != &table) {
579  // for debugging purposes
580  GUM_OP_MOV(HashTable);
581 
582  // first remove the current content of the hashtable and make
583  // the iterators point to end
584  clear();
585 
586  nodes__ = std::move(table.nodes__);
587  safe_iterators__ = std::move(table.safe_iterators__);
588  alloc__ = std::move(table.alloc__);
589  size__ = table.size__;
590  nb_elements__ = table.nb_elements__;
591  hash_func__ = table.hash_func__;
592  resize_policy__ = table.resize_policy__;
593  key_uniqueness_policy__ = table.key_uniqueness_policy__;
594  begin_index__ = table.begin_index__;
595 
596  table.size__ = 0; // necessary if we wish to perform moves iteratively,
597  // i.e. x = std::move ( y ); y = std::move ( z ); ...
598  }
599 
600  return *this;
601  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
std::vector< HashTableConstIteratorSafe< Key, Val > *> safe_iterators__
The list of safe iterators pointing to the hash table.
Definition: hashTable.h:1753
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
friend class HashTable
Friends to optimize the access to data, iterators must be friends.
Definition: hashTable.h:1698
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
void clear()
Removes all the elements in the hash table.
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721

◆ operator==()

template<typename Key, typename Val, typename Alloc >
template<typename OtherAlloc >
bool gum::HashTable< Key, Val, Alloc >::operator== ( const HashTable< Key, Val, OtherAlloc > &  from) const

Checks whether two hashtables contain the same elements.

Two hashtables are considered equal if they contain the identical pairs (key,val). Two pairs are identical if their keys have the same hashed value, these two keys are equal in the sense of ==, and their val's are also equal in the sense of ==.

Parameters
fromThe gum::HashTable to test for equality.
Returns
True if this and from are equal.

Definition at line 1182 of file hashTable_tpl.h.

1183  {
1184  // checks whether the two hashtables contain the same number of elements
1185  if (from.nb_elements__ != nb_elements__) return false;
1186 
1187  // parse this and check that each element also belongs to from
1188  for (auto iter = begin(); iter != end(); ++iter) {
1189  try {
1190  if (iter.val() != from[iter.key()]) return false;
1191  } catch (NotFound&) { return false; }
1192  }
1193 
1194  return true;
1195  }
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724

◆ operator[]() [1/2]

template<typename Key, typename Val , typename Alloc >
INLINE Val & gum::HashTable< Key, Val, Alloc >::operator[] ( const Key &  key)

Returns a reference on the value the key of which is passed in argument.

In case of multiple identical keys in the hash table, the first value encountered is returned. The method runs in constant time.

Parameters
keyThe key of the value to return.
Returns
Returns the value matching the given key.
Exceptions
NotFoundexception is thrown if the element cannot be found.

Definition at line 724 of file hashTable_tpl.h.

724  {
725  return nodes__[hash_func__(key)][key];
726  }
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727

◆ operator[]() [2/2]

template<typename Key, typename Val , typename Alloc >
INLINE const Val & gum::HashTable< Key, Val, Alloc >::operator[] ( const Key &  key) const

returns a reference on the value the key of which is passed in argument

In case of multiple identical keys in the hash table, the first value encountered is returned. The method runs in constant time.

Exceptions
NotFoundexception is thrown if the element cannot be found.

Definition at line 730 of file hashTable_tpl.h.

730  {
731  return nodes__[hash_func__(key)][key];
732  }
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727

◆ reset()

template<typename Key, typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::reset ( const Key &  key)

Removes a property (i.e., remove an element).

Reset removes a property (i.e., a pair (key,val)) if it exists. This is an alias for erase but it is quite convenient when dealing with "dynamic property lists".

Parameters
keyThe property to remove.

Definition at line 1051 of file hashTable_tpl.h.

Referenced by gum::MultiDimSparse< GUM_SCALAR >::set().

1051  {
1052  erase(key);
1053  }
void erase(const Key &key)
Removes a given element from the hash table.
const Key & key(const Key &key) const
Returns a reference on a given key.
+ Here is the caller graph for this function:

◆ resize()

template<typename Key , typename Val , typename Alloc >
void gum::HashTable< Key, Val, Alloc >::resize ( Size  new_size)

Changes the number of slots in the 'nodes' vector of the hash table.

Usually, method resize enables the user to resize manually the hashtable. When in automatic resize mode, the function will actually resize the table only if resizing policy is compatible with the new size, i.e., the new size is not so small that there would be too many elements per slot in the table (this would lead to a significant loss in performance). However, the resizing policy may be changed by using method setResizePolicy. The method runs in linear time in the size of the hashtable. Upon memory allocation problem, the fuction guarantees that no data is lost and that the hash table and its iterators are in a coherent state. In such a case, a bad_alloc exception is thrown.

Parameters
new_sizeThe new number of slots in the gum::HashTable.

Definition at line 772 of file hashTable_tpl.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::create__(), and gum::BayesBall::relevantPotentials().

772  {
773  // new_size must be >= 2 else all the bits of the hash function are lost
774  new_size = std::max(Size(2), new_size);
775 
776  // find the real size for allocation (the smallest power of 2 greater
777  // than or equal to new_size) and get its base-2 logarithm
778  int log_size = hashTableLog2__(new_size);
779  new_size = Size(1) << log_size;
780 
781  // check if the new size is different from the actual size
782  // if not, nothing else need be done
783 
784  if (new_size != size__) {
785  // under automatic resize policy, check if the new size leaves
786  // enough space for storing all the current elements
787  if (!resize_policy__
788  || (nb_elements__
790  // create a new array of nodes__ to store the elements
791  std::vector< HashTableList< Key, Val, Alloc > > new_nodes(new_size);
792 
793  for (auto& list: new_nodes) {
794  list.setAllocator(alloc__);
795  }
796 
797  // set the new hash function
798  hash_func__.resize(new_size);
799 
800  // put all the elements of the current nodes__ array into the new one
801  Bucket* bucket;
802  Size new_hashed_key;
803 
804  for (Size i = Size(0); i < size__; ++i) {
805  while ((bucket = nodes__[i].deb_list__) != nullptr) {
806  // compute the new hashed key
807  new_hashed_key = hash_func__(bucket->key());
808 
809  // remove the bucket from the list of buckets of the current
810  // node vector
811  nodes__[i].deb_list__ = bucket->next;
812 
813  // put the bucket into the new nodes__ vector
814  new_nodes[new_hashed_key].insert(bucket);
815  }
816  }
817 
818  // update the size of the hash table
819  size__ = new_size;
820  begin_index__ = std::numeric_limits< Size >::max();
821 
822  // substitute the current nodes__ array by the new one
823  std::swap(nodes__, new_nodes);
824 
825  // update the iterators
826  for (auto iter: safe_iterators__) {
827  if (iter->bucket__)
828  iter->index__ = hash_func__(iter->bucket__->key());
829  else {
830  iter->next_bucket__ = nullptr;
831  iter->index__ = 0;
832  }
833  }
834  }
835  }
836  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
static constexpr Size default_mean_val_by_slot
The average number of elements admissible by slots.
Definition: hashTable.h:87
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730
std::vector< HashTableConstIteratorSafe< Key, Val > *> safe_iterators__
The list of safe iterators pointing to the hash table.
Definition: hashTable.h:1753
void swap(HashTable< LpCol, double > *&a, HashTable< LpCol, double > *&b)
Swap the addresses of two pointers to hashTables.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
unsigned int hashTableLog2__(const Size nb)
Returns the size in bits - 1 necessary to store the smallest power of 2 greater than or equal to nb...
BucketAllocator alloc__
The allocator for the buckets.
Definition: hashTable.h:1763
Size begin_index__
Returns where the begin index should be.
Definition: hashTable.h:1749
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
Size size__
The number of nodes in vector &#39;__nodes&#39;.
Definition: hashTable.h:1721
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48
+ Here is the caller graph for this function:

◆ resizePolicy()

template<typename Key , typename Val , typename Alloc >
INLINE bool gum::HashTable< Key, Val, Alloc >::resizePolicy ( ) const
noexcept

Returns the current resizing policy.

Returns
Returns the current resizing policy.

Definition at line 756 of file hashTable_tpl.h.

756  {
757  return resize_policy__;
758  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730

◆ set()

template<typename Key, typename Val, typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::set ( const Key &  key,
const Val &  default_value 
)

Add a new property or modify it if it already existed.

When used as a "dynamic property list", it may be convenient to use this function. Function set inserts a new pair (key,val) if the key does not already exists, or it changes the value associated with key if a pair (key,val) already exists in the hash table.

Parameters
keyThe key of the value to add or set.
default_valueThe value to set or add.

Definition at line 981 of file hashTable_tpl.h.

Referenced by gum::SmallObjectAllocator::allocate(), and gum::MultiDimSparse< GUM_SCALAR >::set().

981  {
982  Bucket* bucket = nodes__[hash_func__(key)].bucket(key);
983 
984  if (bucket == nullptr)
985  insert(key, value);
986  else
987  bucket->val() = value;
988  }
HashTableBucket< Key, Val > Bucket
The buckets where data are stored.
Definition: hashTable.h:700
const Key & key(const Key &key) const
Returns a reference on a given key.
std::vector< HashTableList< Key, Val, Alloc > > nodes__
The hash table is represented as a vector of chained lists.
Definition: hashTable.h:1718
HashFunc< Key > hash_func__
The function used to hash keys (may change when the table is resized).
Definition: hashTable.h:1727
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
+ Here is the caller graph for this function:

◆ setKeyUniquenessPolicy()

template<typename Key , typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::setKeyUniquenessPolicy ( const bool  new_policy)
noexcept

Enables the user to change dynamically the policy for checking whether there can exist several elements in the table with identical keys.

By default, we should always check that there does not exist duplicate keys. However, this test slows the insertion of elements in the table. So, when we know for sure that no duplicate key will be entered into the table, we may avoid uniqueness checks.

Warning
When setting the key policy to "uniqueness", the function does not check whether there are already different elements with identical keys in the table. It thus only ensures that elements inserted from now on will have unique keys.

Definition at line 761 of file hashTable_tpl.h.

Referenced by gum::SmallObjectAllocator::SmallObjectAllocator().

762  {
763  key_uniqueness_policy__ = new_policy;
764  }
bool key_uniqueness_policy__
Shall we check for key uniqueness in the table?
Definition: hashTable.h:1733
+ Here is the caller graph for this function:

◆ setResizePolicy()

template<typename Key , typename Val , typename Alloc >
INLINE void gum::HashTable< Key, Val, Alloc >::setResizePolicy ( const bool  new_policy)
noexcept

Enables the user to change dynamically the resizing policy.

In most cases, this should be useless. However, when available memory becomes rare, avoiding automatic resizing may speed-up new insertions in the table.

Warning
This function never resizes the hashtable by itself: even if you set the new policy to be an automatic resizing and the number of elements in the table is sufficiently high that we should resize the table, function setResizePolicy won't perform this resizing. The resizing will happen only if you insert a new element or if use method resize.
Parameters
new_policyThe new resizing policy, true implies automatic resizing.

Definition at line 750 of file hashTable_tpl.h.

751  {
752  resize_policy__ = new_policy;
753  }
bool resize_policy__
Is resizing performed automatically?
Definition: hashTable.h:1730

◆ size()

template<typename Key , typename Val , typename Alloc >
INLINE Size gum::HashTable< Key, Val, Alloc >::size ( ) const
noexcept

Returns the number of elements stored into the hashtable.

The method runs in constant time.

Returns
Returns the number of elements stored into the hashtable.

Definition at line 735 of file hashTable_tpl.h.

Referenced by gum::credal::CredalNet< GUM_SCALAR >::approximatedBinarization(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrASize(), gum::ContingencyTable< Idx, GUM_SCALAR >::attrBSize(), gum::HashTable< Val, Size, IndexAllocator >::clearIterators__(), gum::credal::InferenceEngine< GUM_SCALAR >::computeEpsilon_(), gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::insertEvidence__(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator*(), gum::Set< gum::Potential< GUM_SCALAR > * >::operator==(), gum::MultiDimSparse< GUM_SCALAR >::realSize(), gum::DAGCycleDetector::setDAG(), and gum::credal::CredalNet< GUM_SCALAR >::sort_varType__().

735  {
736  return nb_elements__;
737  }
Size nb_elements__
Number of elements of type Val stored in the hash table.
Definition: hashTable.h:1724
+ Here is the caller graph for this function:

Friends And Related Function Documentation

◆ HashTable

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename K , typename V , typename A >
friend class HashTable
friend

Friends to optimize the access to data, iterators must be friends.

Definition at line 1698 of file hashTable.h.

◆ Bijection

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
template<typename T1 , typename T2 , typename A >
friend class Bijection
friend

For bijections to quickly access data.

Definition at line 1711 of file hashTable.h.

◆ HashTableConstIterator< Key, Val >

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
friend class HashTableConstIterator< Key, Val >
friend

Friends to optimize the access to data, iterators must be friends.

Definition at line 1700 of file hashTable.h.

◆ HashTableConstIteratorSafe< Key, Val >

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
friend class HashTableConstIteratorSafe< Key, Val >
friend

Friends to optimize the access to data, iterators must be friends.

Definition at line 1702 of file hashTable.h.

◆ HashTableIterator< Key, Val >

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
friend class HashTableIterator< Key, Val >
friend

Friends to optimize the access to data, iterators must be friends.

Definition at line 1699 of file hashTable.h.

◆ HashTableIteratorSafe< Key, Val >

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
friend class HashTableIteratorSafe< Key, Val >
friend

Friends to optimize the access to data, iterators must be friends.

Definition at line 1701 of file hashTable.h.

◆ operator<< [1/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
std::ostream& operator<< ( std::ostream &  s,
const HashTable< Key, Val, Alloc > &  table 
)
friend

Prints the content of a gum::HashTable in the stream.

Definition at line 1241 of file hashTable_tpl.h.

1242  {
1243  bool deja = false;
1244  stream << "{";
1245 
1246  for (Size i = Size(0); i < table.size__; ++i)
1247  for (auto ptr = table.nodes__[i].deb_list__; ptr; ptr = ptr->next) {
1248  if (deja) stream << " , ";
1249 
1250  stream << ptr->key() << "=>" << ptr->val();
1251 
1252  deja = true;
1253  }
1254 
1255  stream << "}";
1256 
1257  return stream;
1258  }
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

◆ operator<< [2/2]

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
std::ostream& operator<< ( std::ostream &  s,
const HashTable< Key *, Val, Alloc > &  table 
)
friend

Prints the content of a gum::HashTable with pointers key in the stream.

Definition at line 1261 of file hashTable_tpl.h.

1262  {
1263  bool deja = false;
1264  stream << "{";
1265 
1266  for (Size i = Size(0); i < table.size__; ++i)
1267  for (auto ptr = table.nodes__[i].deb_list__; ptr; ptr = ptr->next) {
1268  if (deja) stream << " , ";
1269 
1270  stream << ptr->key() << "=>" << ptr->val();
1271 
1272  deja = true;
1273  }
1274 
1275  stream << "}";
1276 
1277  return stream;
1278  }
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:48

Member Data Documentation

◆ alloc__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
BucketAllocator gum::HashTable< Key, Val, Alloc >::alloc__
private

The allocator for the buckets.

Warning
the allocator field should compulsorily be the last of field of the class. As such, for K and V fixed, all hashTable<K,V,A> are the same (up to the allocator) for all allocators A. This feature proves useful to avoid passing the allocator as a template parameter to iterators.

Definition at line 1763 of file hashTable.h.

◆ begin_index__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
Size gum::HashTable< Key, Val, Alloc >::begin_index__ {std::numeric_limits< Size >::max()}
mutableprivate

Returns where the begin index should be.

Beware: the beginning of a HashTable is the end of its nodes__ vector, i.e., the Bucket at the highest index in nodes__. This enables a slightly faster parsing than if it were the lowest index.

Warning
std::numeric_limits<Size>::max() means that we do not know where the beginning of the table really is (this can mean either that there is not yet any element in the hash table or that an erase operation has been performed and that we lost track of the element that should correspond to the begin().
Returns
Returns where the begin index should be.

Definition at line 1749 of file hashTable.h.

Referenced by gum::HashTableConstIterator< Key, bool >::HashTableConstIterator(), gum::HashTableConstIteratorSafe< const gum::DiscreteVariable *, Idx >::HashTableConstIteratorSafe(), and gum::HashTable< Val, Size, IndexAllocator >::operator=().

◆ hash_func__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
HashFunc< Key > gum::HashTable< Key, Val, Alloc >::hash_func__
private

The function used to hash keys (may change when the table is resized).

Definition at line 1727 of file hashTable.h.

◆ key_uniqueness_policy__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
bool gum::HashTable< Key, Val, Alloc >::key_uniqueness_policy__ {true}
private

Shall we check for key uniqueness in the table?

Definition at line 1733 of file hashTable.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::operator=().

◆ nb_elements__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
Size gum::HashTable< Key, Val, Alloc >::nb_elements__ {Size(0)}
private

Number of elements of type Val stored in the hash table.

Definition at line 1724 of file hashTable.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::copy__(), and gum::HashTable< Val, Size, IndexAllocator >::operator==().

◆ nodes__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
std::vector< HashTableList< Key, Val, Alloc > > gum::HashTable< Key, Val, Alloc >::nodes__
private

The hash table is represented as a vector of chained lists.

'__nodes' is this very vector.

Definition at line 1718 of file hashTable.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::copy__(), and gum::operator<<().

◆ resize_policy__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
bool gum::HashTable< Key, Val, Alloc >::resize_policy__ {true}
private

Is resizing performed automatically?

Definition at line 1730 of file hashTable.h.

Referenced by gum::HashTable< Val, Size, IndexAllocator >::operator=().

◆ safe_iterators__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
std::vector< HashTableConstIteratorSafe< Key, Val >* > gum::HashTable< Key, Val, Alloc >::safe_iterators__
mutableprivate

The list of safe iterators pointing to the hash table.

Definition at line 1753 of file hashTable.h.

◆ size__

template<typename Key, typename Val, typename Alloc = std::allocator< std::pair< Key, Val > >>
Size gum::HashTable< Key, Val, Alloc >::size__
private

The documentation for this class was generated from the following files: