node_hash_set.h
Go to the documentation of this file.
1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: node_hash_set.h
17 // -----------------------------------------------------------------------------
18 //
19 // An `absl::node_hash_set<T>` is an unordered associative container designed to
20 // be a more efficient replacement for `std::unordered_set`. Like
21 // `unordered_set`, search, insertion, and deletion of map elements can be done
22 // as an `O(1)` operation. However, `node_hash_set` (and other unordered
23 // associative containers known as the collection of Abseil "Swiss tables")
24 // contain other optimizations that result in both memory and computation
25 // advantages.
26 //
27 // In most cases, your default choice for a hash table should be a map of type
28 // `flat_hash_map` or a set of type `flat_hash_set`. However, if you need
29 // pointer stability, a `node_hash_set` should be your preferred choice. As
30 // well, if you are migrating your code from using `std::unordered_set`, a
31 // `node_hash_set` should be an easy migration. Consider migrating to
32 // `node_hash_set` and perhaps converting to a more efficient `flat_hash_set`
33 // upon further review.
34 
35 #ifndef ABSL_CONTAINER_NODE_HASH_SET_H_
36 #define ABSL_CONTAINER_NODE_HASH_SET_H_
37 
38 #include <type_traits>
39 
41 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
43 #include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
44 #include "absl/memory/memory.h"
45 
46 namespace absl {
47 namespace container_internal {
48 template <typename T>
50 } // namespace container_internal
51 
52 // -----------------------------------------------------------------------------
53 // absl::node_hash_set
54 // -----------------------------------------------------------------------------
55 //
56 // An `absl::node_hash_set<T>` is an unordered associative container which
57 // has been optimized for both speed and memory footprint in most common use
58 // cases. Its interface is similar to that of `std::unordered_set<T>` with the
59 // following notable differences:
60 //
61 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
62 // `insert()`, provided that the map is provided a compatible heterogeneous
63 // hashing function and equality operator.
64 // * Contains a `capacity()` member function indicating the number of element
65 // slots (open, deleted, and empty) within the hash set.
66 // * Returns `void` from the `erase(iterator)` overload.
67 //
68 // By default, `node_hash_set` uses the `absl::Hash` hashing framework.
69 // All fundamental and Abseil types that support the `absl::Hash` framework have
70 // a compatible equality operator for comparing insertions into `node_hash_set`.
71 // If your type is not yet supported by the `absl::Hash` framework, see
72 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
73 // types.
74 //
75 // Example:
76 //
77 // // Create a node hash set of three strings
78 // absl::node_hash_map<std::string, std::string> ducks =
79 // {"huey", "dewey"}, "louie"};
80 //
81 // // Insert a new element into the node hash map
82 // ducks.insert("donald"};
83 //
84 // // Force a rehash of the node hash map
85 // ducks.rehash(0);
86 //
87 // // See if "dewey" is present
88 // if (ducks.contains("dewey")) {
89 // std::cout << "We found dewey!" << std::endl;
90 // }
91 template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
92  class Eq = absl::container_internal::hash_default_eq<T>,
93  class Alloc = std::allocator<T>>
96  absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> {
98 
99  public:
100  // Constructors and Assignment Operators
101  //
102  // A node_hash_set supports the same overload set as `std::unordered_map`
103  // for construction and assignment:
104  //
105  // * Default constructor
106  //
107  // // No allocation for the table's elements is made.
108  // absl::node_hash_set<std::string> set1;
109  //
110  // * Initializer List constructor
111  //
112  // absl::node_hash_set<std::string> set2 =
113  // {{"huey"}, {"dewey"}, {"louie"},};
114  //
115  // * Copy constructor
116  //
117  // absl::node_hash_set<std::string> set3(set2);
118  //
119  // * Copy assignment operator
120  //
121  // // Hash functor and Comparator are copied as well
122  // absl::node_hash_set<std::string> set4;
123  // set4 = set3;
124  //
125  // * Move constructor
126  //
127  // // Move is guaranteed efficient
128  // absl::node_hash_set<std::string> set5(std::move(set4));
129  //
130  // * Move assignment operator
131  //
132  // // May be efficient if allocators are compatible
133  // absl::node_hash_set<std::string> set6;
134  // set6 = std::move(set5);
135  //
136  // * Range constructor
137  //
138  // std::vector<std::string> v = {"a", "b"};
139  // absl::node_hash_set<std::string> set7(v.begin(), v.end());
141  using Base::Base;
142 
143  // node_hash_set::begin()
144  //
145  // Returns an iterator to the beginning of the `node_hash_set`.
146  using Base::begin;
147 
148  // node_hash_set::cbegin()
149  //
150  // Returns a const iterator to the beginning of the `node_hash_set`.
151  using Base::cbegin;
152 
153  // node_hash_set::cend()
154  //
155  // Returns a const iterator to the end of the `node_hash_set`.
156  using Base::cend;
157 
158  // node_hash_set::end()
159  //
160  // Returns an iterator to the end of the `node_hash_set`.
161  using Base::end;
162 
163  // node_hash_set::capacity()
164  //
165  // Returns the number of element slots (assigned, deleted, and empty)
166  // available within the `node_hash_set`.
167  //
168  // NOTE: this member function is particular to `absl::node_hash_set` and is
169  // not provided in the `std::unordered_map` API.
170  using Base::capacity;
171 
172  // node_hash_set::empty()
173  //
174  // Returns whether or not the `node_hash_set` is empty.
175  using Base::empty;
176 
177  // node_hash_set::max_size()
178  //
179  // Returns the largest theoretical possible number of elements within a
180  // `node_hash_set` under current memory constraints. This value can be thought
181  // of the largest value of `std::distance(begin(), end())` for a
182  // `node_hash_set<T>`.
183  using Base::max_size;
184 
185  // node_hash_set::size()
186  //
187  // Returns the number of elements currently within the `node_hash_set`.
188  using Base::size;
189 
190  // node_hash_set::clear()
191  //
192  // Removes all elements from the `node_hash_set`. Invalidates any references,
193  // pointers, or iterators referring to contained elements.
194  //
195  // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
196  // the underlying buffer call `erase(begin(), end())`.
197  using Base::clear;
198 
199  // node_hash_set::erase()
200  //
201  // Erases elements within the `node_hash_set`. Erasing does not trigger a
202  // rehash. Overloads are listed below.
203  //
204  // void erase(const_iterator pos):
205  //
206  // Erases the element at `position` of the `node_hash_set`, returning
207  // `void`.
208  //
209  // NOTE: this return behavior is different than that of STL containers in
210  // general and `std::unordered_map` in particular.
211  //
212  // iterator erase(const_iterator first, const_iterator last):
213  //
214  // Erases the elements in the open interval [`first`, `last`), returning an
215  // iterator pointing to `last`.
216  //
217  // size_type erase(const key_type& key):
218  //
219  // Erases the element with the matching key, if it exists.
220  using Base::erase;
221 
222  // node_hash_set::insert()
223  //
224  // Inserts an element of the specified value into the `node_hash_set`,
225  // returning an iterator pointing to the newly inserted element, provided that
226  // an element with the given key does not already exist. If rehashing occurs
227  // due to the insertion, all iterators are invalidated. Overloads are listed
228  // below.
229  //
230  // std::pair<iterator,bool> insert(const T& value):
231  //
232  // Inserts a value into the `node_hash_set`. Returns a pair consisting of an
233  // iterator to the inserted element (or to the element that prevented the
234  // insertion) and a bool denoting whether the insertion took place.
235  //
236  // std::pair<iterator,bool> insert(T&& value):
237  //
238  // Inserts a moveable value into the `node_hash_set`. Returns a pair
239  // consisting of an iterator to the inserted element (or to the element that
240  // prevented the insertion) and a bool denoting whether the insertion took
241  // place.
242  //
243  // iterator insert(const_iterator hint, const T& value):
244  // iterator insert(const_iterator hint, T&& value):
245  //
246  // Inserts a value, using the position of `hint` as a non-binding suggestion
247  // for where to begin the insertion search. Returns an iterator to the
248  // inserted element, or to the existing element that prevented the
249  // insertion.
250  //
251  // void insert(InputIterator first, InputIterator last):
252  //
253  // Inserts a range of values [`first`, `last`).
254  //
255  // NOTE: Although the STL does not specify which element may be inserted if
256  // multiple keys compare equivalently, for `node_hash_set` we guarantee the
257  // first match is inserted.
258  //
259  // void insert(std::initializer_list<T> ilist):
260  //
261  // Inserts the elements within the initializer list `ilist`.
262  //
263  // NOTE: Although the STL does not specify which element may be inserted if
264  // multiple keys compare equivalently within the initializer list, for
265  // `node_hash_set` we guarantee the first match is inserted.
266  using Base::insert;
267 
268  // node_hash_set::emplace()
269  //
270  // Inserts an element of the specified value by constructing it in-place
271  // within the `node_hash_set`, provided that no element with the given key
272  // already exists.
273  //
274  // The element may be constructed even if there already is an element with the
275  // key in the container, in which case the newly constructed element will be
276  // destroyed immediately.
277  //
278  // If rehashing occurs due to the insertion, all iterators are invalidated.
279  using Base::emplace;
280 
281  // node_hash_set::emplace_hint()
282  //
283  // Inserts an element of the specified value by constructing it in-place
284  // within the `node_hash_set`, using the position of `hint` as a non-binding
285  // suggestion for where to begin the insertion search, and only inserts
286  // provided that no element with the given key already exists.
287  //
288  // The element may be constructed even if there already is an element with the
289  // key in the container, in which case the newly constructed element will be
290  // destroyed immediately.
291  //
292  // If rehashing occurs due to the insertion, all iterators are invalidated.
293  using Base::emplace_hint;
294 
295  // node_hash_set::extract()
296  //
297  // Extracts the indicated element, erasing it in the process, and returns it
298  // as a C++17-compatible node handle. Overloads are listed below.
299  //
300  // node_type extract(const_iterator position):
301  //
302  // Extracts the element at the indicated position and returns a node handle
303  // owning that extracted data.
304  //
305  // node_type extract(const key_type& x):
306  //
307  // Extracts the element with the key matching the passed key value and
308  // returns a node handle owning that extracted data. If the `node_hash_set`
309  // does not contain an element with a matching key, this function returns an
310  // empty node handle.
311  using Base::extract;
312 
313  // node_hash_set::merge()
314  //
315  // Extracts elements from a given `source` flat hash map into this
316  // `node_hash_set`. If the destination `node_hash_set` already contains an
317  // element with an equivalent key, that element is not extracted.
318  using Base::merge;
319 
320  // node_hash_set::swap(node_hash_set& other)
321  //
322  // Exchanges the contents of this `node_hash_set` with those of the `other`
323  // flat hash map, avoiding invocation of any move, copy, or swap operations on
324  // individual elements.
325  //
326  // All iterators and references on the `node_hash_set` remain valid, excepting
327  // for the past-the-end iterator, which is invalidated.
328  //
329  // `swap()` requires that the flat hash set's hashing and key equivalence
330  // functions be Swappable, and are exchaged using unqualified calls to
331  // non-member `swap()`. If the map's allocator has
332  // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
333  // set to `true`, the allocators are also exchanged using an unqualified call
334  // to non-member `swap()`; otherwise, the allocators are not swapped.
335  using Base::swap;
336 
337  // node_hash_set::rehash(count)
338  //
339  // Rehashes the `node_hash_set`, setting the number of slots to be at least
340  // the passed value. If the new number of slots increases the load factor more
341  // than the current maximum load factor
342  // (`count` < `size()` / `max_load_factor()`), then the new number of slots
343  // will be at least `size()` / `max_load_factor()`.
344  //
345  // To force a rehash, pass rehash(0).
346  //
347  // NOTE: unlike behavior in `std::unordered_set`, references are also
348  // invalidated upon a `rehash()`.
349  using Base::rehash;
350 
351  // node_hash_set::reserve(count)
352  //
353  // Sets the number of slots in the `node_hash_set` to the number needed to
354  // accommodate at least `count` total elements without exceeding the current
355  // maximum load factor, and may rehash the container if needed.
356  using Base::reserve;
357 
358  // node_hash_set::contains()
359  //
360  // Determines whether an element comparing equal to the given `key` exists
361  // within the `node_hash_set`, returning `true` if so or `false` otherwise.
362  using Base::contains;
363 
364  // node_hash_set::count(const Key& key) const
365  //
366  // Returns the number of elements comparing equal to the given `key` within
367  // the `node_hash_set`. note that this function will return either `1` or `0`
368  // since duplicate elements are not allowed within a `node_hash_set`.
369  using Base::count;
370 
371  // node_hash_set::equal_range()
372  //
373  // Returns a closed range [first, last], defined by a `std::pair` of two
374  // iterators, containing all elements with the passed key in the
375  // `node_hash_set`.
376  using Base::equal_range;
377 
378  // node_hash_set::find()
379  //
380  // Finds an element with the passed `key` within the `node_hash_set`.
381  using Base::find;
382 
383  // node_hash_set::bucket_count()
384  //
385  // Returns the number of "buckets" within the `node_hash_set`. Note that
386  // because a flat hash map contains all elements within its internal storage,
387  // this value simply equals the current capacity of the `node_hash_set`.
388  using Base::bucket_count;
389 
390  // node_hash_set::load_factor()
391  //
392  // Returns the current load factor of the `node_hash_set` (the average number
393  // of slots occupied with a value within the hash map).
394  using Base::load_factor;
395 
396  // node_hash_set::max_load_factor()
397  //
398  // Manages the maximum load factor of the `node_hash_set`. Overloads are
399  // listed below.
400  //
401  // float node_hash_set::max_load_factor()
402  //
403  // Returns the current maximum load factor of the `node_hash_set`.
404  //
405  // void node_hash_set::max_load_factor(float ml)
406  //
407  // Sets the maximum load factor of the `node_hash_set` to the passed value.
408  //
409  // NOTE: This overload is provided only for API compatibility with the STL;
410  // `node_hash_set` will ignore any set load factor and manage its rehashing
411  // internally as an implementation detail.
412  using Base::max_load_factor;
413 
414  // node_hash_set::get_allocator()
415  //
416  // Returns the allocator function associated with this `node_hash_set`.
417  using Base::get_allocator;
418 
419  // node_hash_set::hash_function()
420  //
421  // Returns the hashing function used to hash the keys within this
422  // `node_hash_set`.
423  using Base::hash_function;
424 
425  // node_hash_set::key_eq()
426  //
427  // Returns the function used for comparing keys equality.
428  using Base::key_eq;
429 
430  ABSL_DEPRECATED("Call `hash_function()` instead.")
431  typename Base::hasher hash_funct() { return this->hash_function(); }
432 
433  ABSL_DEPRECATED("Call `rehash()` instead.")
434  void resize(typename Base::size_type hint) { this->rehash(hint); }
435 };
436 
437 namespace container_internal {
438 
439 template <class T>
440 struct NodeHashSetPolicy
441  : absl::container_internal::node_hash_policy<T&, NodeHashSetPolicy<T>> {
442  using key_type = T;
443  using init_type = T;
444  using constant_iterators = std::true_type;
445 
446  template <class Allocator, class... Args>
447  static T* new_element(Allocator* alloc, Args&&... args) {
448  using ValueAlloc =
449  typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
450  ValueAlloc value_alloc(*alloc);
451  T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
453  std::forward<Args>(args)...);
454  return res;
455  }
456 
457  template <class Allocator>
458  static void delete_element(Allocator* alloc, T* elem) {
459  using ValueAlloc =
460  typename absl::allocator_traits<Allocator>::template rebind_alloc<T>;
461  ValueAlloc value_alloc(*alloc);
464  }
465 
466  template <class F, class... Args>
468  std::declval<F>(), std::declval<Args>()...))
469  apply(F&& f, Args&&... args) {
471  std::forward<F>(f), std::forward<Args>(args)...);
472  }
473 
474  static size_t element_space_used(const T*) { return sizeof(T); }
475 };
476 } // namespace container_internal
477 
478 namespace container_algorithm_internal {
479 
480 // Specialization of trait in absl/algorithm/container.h
481 template <class Key, class Hash, class KeyEqual, class Allocator>
482 struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>>
483  : std::true_type {};
484 
485 } // namespace container_algorithm_internal
486 } // namespace absl
487 
488 #endif // ABSL_CONTAINER_NODE_HASH_SET_H_
hash_default_eq< T > key_eq
char * begin
raw_hash_set() noexcept(std::is_nothrow_default_constructible< hasher >::value &&std::is_nothrow_default_constructible< key_equal >::value &&std::is_nothrow_default_constructible< allocator_type >::value)
Definition: raw_hash_set.h:707
static void deallocate(Alloc &a, pointer p, size_type n)
Definition: memory.h:524
static void delete_element(Allocator *alloc, T *elem)
decltype(std::declval< F >()(std::declval< const Arg & >(), std::declval< Arg >())) DecomposeValue(F &&f, Arg &&arg)
static void destroy(Alloc &a, T *p)
Definition: memory.h:542
static pointer allocate(Alloc &a, size_type n)
Definition: memory.h:509
static size_t element_space_used(const T *)
char * end
Definition: algorithm.h:29
static T * new_element(Allocator *alloc, Args &&...args)
ABSL_DEPRECATED("absl::bit_cast type requirements were violated. Update the types being ""used such that they are the same size and are both TriviallyCopyable.") inline Dest bit_cast(const Source &source)
Definition: casts.h:168
void swap(absl::InlinedVector< T, N, A > &a, absl::InlinedVector< T, N, A > &b) noexcept(noexcept(a.swap(b)))
auto apply(Functor &&functor, Tuple &&t) -> decltype(utility_internal::apply_helper(absl::forward< Functor >(functor), absl::forward< Tuple >(t), absl::make_index_sequence< std::tuple_size< typename std::remove_reference< Tuple >::type >::value >
Definition: utility.h:287
uintptr_t size
typename node_hash_set::raw_hash_set Base
Definition: node_hash_set.h:97
std::allocator< int > alloc
static void construct(Alloc &a, T *p, Args &&...args)
Definition: memory.h:534


abseil_cpp
Author(s):
autogenerated on Tue Jun 18 2019 19:44:36