• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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: flat_hash_set.h
17 // -----------------------------------------------------------------------------
18 //
19 // An `absl::flat_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 set elements can be done
22 // as an `O(1)` operation. However, `flat_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 set should be a set of type
28 // `flat_hash_set`.
29 #ifndef ABSL_CONTAINER_FLAT_HASH_SET_H_
30 #define ABSL_CONTAINER_FLAT_HASH_SET_H_
31 
32 #include <type_traits>
33 #include <utility>
34 
35 #include "absl/algorithm/container.h"
36 #include "absl/base/macros.h"
37 #include "absl/container/internal/container_memory.h"
38 #include "absl/container/internal/hash_function_defaults.h"  // IWYU pragma: export
39 #include "absl/container/internal/raw_hash_set.h"  // IWYU pragma: export
40 #include "absl/memory/memory.h"
41 
42 namespace absl {
43 ABSL_NAMESPACE_BEGIN
44 namespace container_internal {
45 template <typename T>
46 struct FlatHashSetPolicy;
47 }  // namespace container_internal
48 
49 // -----------------------------------------------------------------------------
50 // absl::flat_hash_set
51 // -----------------------------------------------------------------------------
52 //
53 // An `absl::flat_hash_set<T>` is an unordered associative container which has
54 // been optimized for both speed and memory footprint in most common use cases.
55 // Its interface is similar to that of `std::unordered_set<T>` with the
56 // following notable differences:
57 //
58 // * Requires keys that are CopyConstructible
59 // * Supports heterogeneous lookup, through `find()` and `insert()`, provided
60 //   that the set is provided a compatible heterogeneous hashing function and
61 //   equality operator.
62 // * Invalidates any references and pointers to elements within the table after
63 //   `rehash()`.
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, `flat_hash_set` uses the `absl::Hash` hashing framework. All
69 // fundamental and Abseil types that support the `absl::Hash` framework have a
70 // compatible equality operator for comparing insertions into `flat_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 // Using `absl::flat_hash_set` at interface boundaries in dynamically loaded
76 // libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
77 // be randomized across dynamically loaded libraries.
78 //
79 // NOTE: A `flat_hash_set` stores its keys directly inside its implementation
80 // array to avoid memory indirection. Because a `flat_hash_set` is designed to
81 // move data when rehashed, set keys will not retain pointer stability. If you
82 // require pointer stability, consider using
83 // `absl::flat_hash_set<std::unique_ptr<T>>`. If your type is not moveable and
84 // you require pointer stability, consider `absl::node_hash_set` instead.
85 //
86 // Example:
87 //
88 //   // Create a flat hash set of three strings
89 //   absl::flat_hash_set<std::string> ducks =
90 //     {"huey", "dewey", "louie"};
91 //
92 //  // Insert a new element into the flat hash set
93 //  ducks.insert("donald");
94 //
95 //  // Force a rehash of the flat hash set
96 //  ducks.rehash(0);
97 //
98 //  // See if "dewey" is present
99 //  if (ducks.contains("dewey")) {
100 //    std::cout << "We found dewey!" << std::endl;
101 //  }
102 template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
103           class Eq = absl::container_internal::hash_default_eq<T>,
104           class Allocator = std::allocator<T>>
105 class flat_hash_set
106     : public absl::container_internal::raw_hash_set<
107           absl::container_internal::FlatHashSetPolicy<T>, Hash, Eq, Allocator> {
108   using Base = typename flat_hash_set::raw_hash_set;
109 
110  public:
111   // Constructors and Assignment Operators
112   //
113   // A flat_hash_set supports the same overload set as `std::unordered_set`
114   // for construction and assignment:
115   //
116   // *  Default constructor
117   //
118   //    // No allocation for the table's elements is made.
119   //    absl::flat_hash_set<std::string> set1;
120   //
121   // * Initializer List constructor
122   //
123   //   absl::flat_hash_set<std::string> set2 =
124   //       {{"huey"}, {"dewey"}, {"louie"},};
125   //
126   // * Copy constructor
127   //
128   //   absl::flat_hash_set<std::string> set3(set2);
129   //
130   // * Copy assignment operator
131   //
132   //  // Hash functor and Comparator are copied as well
133   //  absl::flat_hash_set<std::string> set4;
134   //  set4 = set3;
135   //
136   // * Move constructor
137   //
138   //   // Move is guaranteed efficient
139   //   absl::flat_hash_set<std::string> set5(std::move(set4));
140   //
141   // * Move assignment operator
142   //
143   //   // May be efficient if allocators are compatible
144   //   absl::flat_hash_set<std::string> set6;
145   //   set6 = std::move(set5);
146   //
147   // * Range constructor
148   //
149   //   std::vector<std::string> v = {"a", "b"};
150   //   absl::flat_hash_set<std::string> set7(v.begin(), v.end());
flat_hash_set()151   flat_hash_set() {}
152   using Base::Base;
153 
154   // flat_hash_set::begin()
155   //
156   // Returns an iterator to the beginning of the `flat_hash_set`.
157   using Base::begin;
158 
159   // flat_hash_set::cbegin()
160   //
161   // Returns a const iterator to the beginning of the `flat_hash_set`.
162   using Base::cbegin;
163 
164   // flat_hash_set::cend()
165   //
166   // Returns a const iterator to the end of the `flat_hash_set`.
167   using Base::cend;
168 
169   // flat_hash_set::end()
170   //
171   // Returns an iterator to the end of the `flat_hash_set`.
172   using Base::end;
173 
174   // flat_hash_set::capacity()
175   //
176   // Returns the number of element slots (assigned, deleted, and empty)
177   // available within the `flat_hash_set`.
178   //
179   // NOTE: this member function is particular to `absl::flat_hash_set` and is
180   // not provided in the `std::unordered_set` API.
181   using Base::capacity;
182 
183   // flat_hash_set::empty()
184   //
185   // Returns whether or not the `flat_hash_set` is empty.
186   using Base::empty;
187 
188   // flat_hash_set::max_size()
189   //
190   // Returns the largest theoretical possible number of elements within a
191   // `flat_hash_set` under current memory constraints. This value can be thought
192   // of the largest value of `std::distance(begin(), end())` for a
193   // `flat_hash_set<T>`.
194   using Base::max_size;
195 
196   // flat_hash_set::size()
197   //
198   // Returns the number of elements currently within the `flat_hash_set`.
199   using Base::size;
200 
201   // flat_hash_set::clear()
202   //
203   // Removes all elements from the `flat_hash_set`. Invalidates any references,
204   // pointers, or iterators referring to contained elements.
205   //
206   // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
207   // the underlying buffer call `erase(begin(), end())`.
208   using Base::clear;
209 
210   // flat_hash_set::erase()
211   //
212   // Erases elements within the `flat_hash_set`. Erasing does not trigger a
213   // rehash. Overloads are listed below.
214   //
215   // void erase(const_iterator pos):
216   //
217   //   Erases the element at `position` of the `flat_hash_set`, returning
218   //   `void`.
219   //
220   //   NOTE: returning `void` in this case is different than that of STL
221   //   containers in general and `std::unordered_set` in particular (which
222   //   return an iterator to the element following the erased element). If that
223   //   iterator is needed, simply post increment the iterator:
224   //
225   //     set.erase(it++);
226   //
227   // iterator erase(const_iterator first, const_iterator last):
228   //
229   //   Erases the elements in the open interval [`first`, `last`), returning an
230   //   iterator pointing to `last`. The special case of calling
231   //   `erase(begin(), end())` resets the reserved growth such that if
232   //   `reserve(N)` has previously been called and there has been no intervening
233   //   call to `clear()`, then after calling `erase(begin(), end())`, it is safe
234   //   to assume that inserting N elements will not cause a rehash.
235   //
236   // size_type erase(const key_type& key):
237   //
238   //   Erases the element with the matching key, if it exists, returning the
239   //   number of elements erased (0 or 1).
240   using Base::erase;
241 
242   // flat_hash_set::insert()
243   //
244   // Inserts an element of the specified value into the `flat_hash_set`,
245   // returning an iterator pointing to the newly inserted element, provided that
246   // an element with the given key does not already exist. If rehashing occurs
247   // due to the insertion, all iterators are invalidated. Overloads are listed
248   // below.
249   //
250   // std::pair<iterator,bool> insert(const T& value):
251   //
252   //   Inserts a value into the `flat_hash_set`. Returns a pair consisting of an
253   //   iterator to the inserted element (or to the element that prevented the
254   //   insertion) and a bool denoting whether the insertion took place.
255   //
256   // std::pair<iterator,bool> insert(T&& value):
257   //
258   //   Inserts a moveable value into the `flat_hash_set`. Returns a pair
259   //   consisting of an iterator to the inserted element (or to the element that
260   //   prevented the insertion) and a bool denoting whether the insertion took
261   //   place.
262   //
263   // iterator insert(const_iterator hint, const T& value):
264   // iterator insert(const_iterator hint, T&& value):
265   //
266   //   Inserts a value, using the position of `hint` as a non-binding suggestion
267   //   for where to begin the insertion search. Returns an iterator to the
268   //   inserted element, or to the existing element that prevented the
269   //   insertion.
270   //
271   // void insert(InputIterator first, InputIterator last):
272   //
273   //   Inserts a range of values [`first`, `last`).
274   //
275   //   NOTE: Although the STL does not specify which element may be inserted if
276   //   multiple keys compare equivalently, for `flat_hash_set` we guarantee the
277   //   first match is inserted.
278   //
279   // void insert(std::initializer_list<T> ilist):
280   //
281   //   Inserts the elements within the initializer list `ilist`.
282   //
283   //   NOTE: Although the STL does not specify which element may be inserted if
284   //   multiple keys compare equivalently within the initializer list, for
285   //   `flat_hash_set` we guarantee the first match is inserted.
286   using Base::insert;
287 
288   // flat_hash_set::emplace()
289   //
290   // Inserts an element of the specified value by constructing it in-place
291   // within the `flat_hash_set`, provided that no element with the given key
292   // already exists.
293   //
294   // The element may be constructed even if there already is an element with the
295   // key in the container, in which case the newly constructed element will be
296   // destroyed immediately.
297   //
298   // If rehashing occurs due to the insertion, all iterators are invalidated.
299   using Base::emplace;
300 
301   // flat_hash_set::emplace_hint()
302   //
303   // Inserts an element of the specified value by constructing it in-place
304   // within the `flat_hash_set`, using the position of `hint` as a non-binding
305   // suggestion for where to begin the insertion search, and only inserts
306   // provided that no element with the given key already exists.
307   //
308   // The element may be constructed even if there already is an element with the
309   // key in the container, in which case the newly constructed element will be
310   // destroyed immediately.
311   //
312   // If rehashing occurs due to the insertion, all iterators are invalidated.
313   using Base::emplace_hint;
314 
315   // flat_hash_set::extract()
316   //
317   // Extracts the indicated element, erasing it in the process, and returns it
318   // as a C++17-compatible node handle. Overloads are listed below.
319   //
320   // node_type extract(const_iterator position):
321   //
322   //   Extracts the element at the indicated position and returns a node handle
323   //   owning that extracted data.
324   //
325   // node_type extract(const key_type& x):
326   //
327   //   Extracts the element with the key matching the passed key value and
328   //   returns a node handle owning that extracted data. If the `flat_hash_set`
329   //   does not contain an element with a matching key, this function returns an
330   //   empty node handle.
331   using Base::extract;
332 
333   // flat_hash_set::merge()
334   //
335   // Extracts elements from a given `source` flat hash set into this
336   // `flat_hash_set`. If the destination `flat_hash_set` already contains an
337   // element with an equivalent key, that element is not extracted.
338   using Base::merge;
339 
340   // flat_hash_set::swap(flat_hash_set& other)
341   //
342   // Exchanges the contents of this `flat_hash_set` with those of the `other`
343   // flat hash set, avoiding invocation of any move, copy, or swap operations on
344   // individual elements.
345   //
346   // All iterators and references on the `flat_hash_set` remain valid, excepting
347   // for the past-the-end iterator, which is invalidated.
348   //
349   // `swap()` requires that the flat hash set's hashing and key equivalence
350   // functions be Swappable, and are exchanged using unqualified calls to
351   // non-member `swap()`. If the set's allocator has
352   // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
353   // set to `true`, the allocators are also exchanged using an unqualified call
354   // to non-member `swap()`; otherwise, the allocators are not swapped.
355   using Base::swap;
356 
357   // flat_hash_set::rehash(count)
358   //
359   // Rehashes the `flat_hash_set`, setting the number of slots to be at least
360   // the passed value. If the new number of slots increases the load factor more
361   // than the current maximum load factor
362   // (`count` < `size()` / `max_load_factor()`), then the new number of slots
363   // will be at least `size()` / `max_load_factor()`.
364   //
365   // To force a rehash, pass rehash(0).
366   //
367   // NOTE: unlike behavior in `std::unordered_set`, references are also
368   // invalidated upon a `rehash()`.
369   using Base::rehash;
370 
371   // flat_hash_set::reserve(count)
372   //
373   // Sets the number of slots in the `flat_hash_set` to the number needed to
374   // accommodate at least `count` total elements without exceeding the current
375   // maximum load factor, and may rehash the container if needed.
376   using Base::reserve;
377 
378   // flat_hash_set::contains()
379   //
380   // Determines whether an element comparing equal to the given `key` exists
381   // within the `flat_hash_set`, returning `true` if so or `false` otherwise.
382   using Base::contains;
383 
384   // flat_hash_set::count(const Key& key) const
385   //
386   // Returns the number of elements comparing equal to the given `key` within
387   // the `flat_hash_set`. note that this function will return either `1` or `0`
388   // since duplicate elements are not allowed within a `flat_hash_set`.
389   using Base::count;
390 
391   // flat_hash_set::equal_range()
392   //
393   // Returns a closed range [first, last], defined by a `std::pair` of two
394   // iterators, containing all elements with the passed key in the
395   // `flat_hash_set`.
396   using Base::equal_range;
397 
398   // flat_hash_set::find()
399   //
400   // Finds an element with the passed `key` within the `flat_hash_set`.
401   using Base::find;
402 
403   // flat_hash_set::bucket_count()
404   //
405   // Returns the number of "buckets" within the `flat_hash_set`. Note that
406   // because a flat hash set contains all elements within its internal storage,
407   // this value simply equals the current capacity of the `flat_hash_set`.
408   using Base::bucket_count;
409 
410   // flat_hash_set::load_factor()
411   //
412   // Returns the current load factor of the `flat_hash_set` (the average number
413   // of slots occupied with a value within the hash set).
414   using Base::load_factor;
415 
416   // flat_hash_set::max_load_factor()
417   //
418   // Manages the maximum load factor of the `flat_hash_set`. Overloads are
419   // listed below.
420   //
421   // float flat_hash_set::max_load_factor()
422   //
423   //   Returns the current maximum load factor of the `flat_hash_set`.
424   //
425   // void flat_hash_set::max_load_factor(float ml)
426   //
427   //   Sets the maximum load factor of the `flat_hash_set` to the passed value.
428   //
429   //   NOTE: This overload is provided only for API compatibility with the STL;
430   //   `flat_hash_set` will ignore any set load factor and manage its rehashing
431   //   internally as an implementation detail.
432   using Base::max_load_factor;
433 
434   // flat_hash_set::get_allocator()
435   //
436   // Returns the allocator function associated with this `flat_hash_set`.
437   using Base::get_allocator;
438 
439   // flat_hash_set::hash_function()
440   //
441   // Returns the hashing function used to hash the keys within this
442   // `flat_hash_set`.
443   using Base::hash_function;
444 
445   // flat_hash_set::key_eq()
446   //
447   // Returns the function used for comparing keys equality.
448   using Base::key_eq;
449 };
450 
451 // erase_if(flat_hash_set<>, Pred)
452 //
453 // Erases all elements that satisfy the predicate `pred` from the container `c`.
454 // Returns the number of erased elements.
455 template <typename T, typename H, typename E, typename A, typename Predicate>
erase_if(flat_hash_set<T,H,E,A> & c,Predicate pred)456 typename flat_hash_set<T, H, E, A>::size_type erase_if(
457     flat_hash_set<T, H, E, A>& c, Predicate pred) {
458   return container_internal::EraseIf(pred, &c);
459 }
460 
461 namespace container_internal {
462 
463 template <class T>
464 struct FlatHashSetPolicy {
465   using slot_type = T;
466   using key_type = T;
467   using init_type = T;
468   using constant_iterators = std::true_type;
469 
470   template <class Allocator, class... Args>
constructFlatHashSetPolicy471   static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
472     absl::allocator_traits<Allocator>::construct(*alloc, slot,
473                                                  std::forward<Args>(args)...);
474   }
475 
476   template <class Allocator>
destroyFlatHashSetPolicy477   static void destroy(Allocator* alloc, slot_type* slot) {
478     absl::allocator_traits<Allocator>::destroy(*alloc, slot);
479   }
480 
elementFlatHashSetPolicy481   static T& element(slot_type* slot) { return *slot; }
482 
483   template <class F, class... Args>
decltypeFlatHashSetPolicy484   static decltype(absl::container_internal::DecomposeValue(
485       std::declval<F>(), std::declval<Args>()...))
486   apply(F&& f, Args&&... args) {
487     return absl::container_internal::DecomposeValue(
488         std::forward<F>(f), std::forward<Args>(args)...);
489   }
490 
space_usedFlatHashSetPolicy491   static size_t space_used(const T*) { return 0; }
492 };
493 }  // namespace container_internal
494 
495 namespace container_algorithm_internal {
496 
497 // Specialization of trait in absl/algorithm/container.h
498 template <class Key, class Hash, class KeyEqual, class Allocator>
499 struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>>
500     : std::true_type {};
501 
502 }  // namespace container_algorithm_internal
503 
504 ABSL_NAMESPACE_END
505 }  // namespace absl
506 
507 #endif  // ABSL_CONTAINER_FLAT_HASH_SET_H_
508