1 // Copyright 2018 The Abseil Authors.
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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.
15 // -----------------------------------------------------------------------------
16 // File: flat_hash_set.h
17 // -----------------------------------------------------------------------------
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
27 // In most cases, your default choice for a hash set should be a set of type
29 #ifndef ABSL_CONTAINER_FLAT_HASH_SET_H_
30 #define ABSL_CONTAINER_FLAT_HASH_SET_H_
32 #include <type_traits>
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"
43 namespace container_internal {
45 struct FlatHashSetPolicy;
46 } // namespace container_internal
48 // -----------------------------------------------------------------------------
49 // absl::flat_hash_set
50 // -----------------------------------------------------------------------------
52 // An `absl::flat_hash_set<T>` is an unordered associative container which has
53 // been optimized for both speed and memory footprint in most common use cases.
54 // Its interface is similar to that of `std::unordered_set<T>` with the
55 // following notable differences:
57 // * Requires keys that are CopyConstructible
58 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
59 // `insert()`, provided that the set is provided a compatible heterogeneous
60 // hashing function and equality operator.
61 // * Invalidates any references and pointers to elements within the table after
63 // * Contains a `capacity()` member function indicating the number of element
64 // slots (open, deleted, and empty) within the hash set.
65 // * Returns `void` from the `erase(iterator)` overload.
67 // By default, `flat_hash_set` uses the `absl::Hash` hashing framework. All
68 // fundamental and Abseil types that support the `absl::Hash` framework have a
69 // compatible equality operator for comparing insertions into `flat_hash_map`.
70 // If your type is not yet supported by the `absl::Hash` framework, see
71 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
74 // NOTE: A `flat_hash_set` stores its keys directly inside its implementation
75 // array to avoid memory indirection. Because a `flat_hash_set` is designed to
76 // move data when rehashed, set keys will not retain pointer stability. If you
77 // require pointer stability, consider using
78 // `absl::flat_hash_set<std::unique_ptr<T>>`. If your type is not moveable and
79 // you require pointer stability, consider `absl::node_hash_set` instead.
83 // // Create a flat hash set of three strings
84 // absl::flat_hash_set<std::string> ducks =
85 // {"huey", "dewey", "louie"};
87 // // Insert a new element into the flat hash set
88 // ducks.insert("donald");
90 // // Force a rehash of the flat hash set
93 // // See if "dewey" is present
94 // if (ducks.contains("dewey")) {
95 // std::cout << "We found dewey!" << std::endl;
97 template <class T, class Hash = absl::container_internal::hash_default_hash<T>,
98 class Eq = absl::container_internal::hash_default_eq<T>,
99 class Allocator = std::allocator<T>>
101 : public absl::container_internal::raw_hash_set<
102 absl::container_internal::FlatHashSetPolicy<T>, Hash, Eq, Allocator> {
103 using Base = typename flat_hash_set::raw_hash_set;
106 // Constructors and Assignment Operators
108 // A flat_hash_set supports the same overload set as `std::unordered_map`
109 // for construction and assignment:
111 // * Default constructor
113 // // No allocation for the table's elements is made.
114 // absl::flat_hash_set<std::string> set1;
116 // * Initializer List constructor
118 // absl::flat_hash_set<std::string> set2 =
119 // {{"huey"}, {"dewey"}, {"louie"},};
121 // * Copy constructor
123 // absl::flat_hash_set<std::string> set3(set2);
125 // * Copy assignment operator
127 // // Hash functor and Comparator are copied as well
128 // absl::flat_hash_set<std::string> set4;
131 // * Move constructor
133 // // Move is guaranteed efficient
134 // absl::flat_hash_set<std::string> set5(std::move(set4));
136 // * Move assignment operator
138 // // May be efficient if allocators are compatible
139 // absl::flat_hash_set<std::string> set6;
140 // set6 = std::move(set5);
142 // * Range constructor
144 // std::vector<std::string> v = {"a", "b"};
145 // absl::flat_hash_set<std::string> set7(v.begin(), v.end());
149 // flat_hash_set::begin()
151 // Returns an iterator to the beginning of the `flat_hash_set`.
154 // flat_hash_set::cbegin()
156 // Returns a const iterator to the beginning of the `flat_hash_set`.
159 // flat_hash_set::cend()
161 // Returns a const iterator to the end of the `flat_hash_set`.
164 // flat_hash_set::end()
166 // Returns an iterator to the end of the `flat_hash_set`.
169 // flat_hash_set::capacity()
171 // Returns the number of element slots (assigned, deleted, and empty)
172 // available within the `flat_hash_set`.
174 // NOTE: this member function is particular to `absl::flat_hash_set` and is
175 // not provided in the `std::unordered_map` API.
176 using Base::capacity;
178 // flat_hash_set::empty()
180 // Returns whether or not the `flat_hash_set` is empty.
183 // flat_hash_set::max_size()
185 // Returns the largest theoretical possible number of elements within a
186 // `flat_hash_set` under current memory constraints. This value can be thought
187 // of the largest value of `std::distance(begin(), end())` for a
188 // `flat_hash_set<T>`.
189 using Base::max_size;
191 // flat_hash_set::size()
193 // Returns the number of elements currently within the `flat_hash_set`.
196 // flat_hash_set::clear()
198 // Removes all elements from the `flat_hash_set`. Invalidates any references,
199 // pointers, or iterators referring to contained elements.
201 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
202 // the underlying buffer call `erase(begin(), end())`.
205 // flat_hash_set::erase()
207 // Erases elements within the `flat_hash_set`. Erasing does not trigger a
208 // rehash. Overloads are listed below.
210 // void erase(const_iterator pos):
212 // Erases the element at `position` of the `flat_hash_set`, returning
215 // NOTE: returning `void` in this case is different than that of STL
216 // containers in general and `std::unordered_set` in particular (which
217 // return an iterator to the element following the erased element). If that
218 // iterator is needed, simply post increment the iterator:
222 // iterator erase(const_iterator first, const_iterator last):
224 // Erases the elements in the open interval [`first`, `last`), returning an
225 // iterator pointing to `last`.
227 // size_type erase(const key_type& key):
229 // Erases the element with the matching key, if it exists.
232 // flat_hash_set::insert()
234 // Inserts an element of the specified value into the `flat_hash_set`,
235 // returning an iterator pointing to the newly inserted element, provided that
236 // an element with the given key does not already exist. If rehashing occurs
237 // due to the insertion, all iterators are invalidated. Overloads are listed
240 // std::pair<iterator,bool> insert(const T& value):
242 // Inserts a value into the `flat_hash_set`. Returns a pair consisting of an
243 // iterator to the inserted element (or to the element that prevented the
244 // insertion) and a bool denoting whether the insertion took place.
246 // std::pair<iterator,bool> insert(T&& value):
248 // Inserts a moveable value into the `flat_hash_set`. Returns a pair
249 // consisting of an iterator to the inserted element (or to the element that
250 // prevented the insertion) and a bool denoting whether the insertion took
253 // iterator insert(const_iterator hint, const T& value):
254 // iterator insert(const_iterator hint, T&& value):
256 // Inserts a value, using the position of `hint` as a non-binding suggestion
257 // for where to begin the insertion search. Returns an iterator to the
258 // inserted element, or to the existing element that prevented the
261 // void insert(InputIterator first, InputIterator last):
263 // Inserts a range of values [`first`, `last`).
265 // NOTE: Although the STL does not specify which element may be inserted if
266 // multiple keys compare equivalently, for `flat_hash_set` we guarantee the
267 // first match is inserted.
269 // void insert(std::initializer_list<T> ilist):
271 // Inserts the elements within the initializer list `ilist`.
273 // NOTE: Although the STL does not specify which element may be inserted if
274 // multiple keys compare equivalently within the initializer list, for
275 // `flat_hash_set` we guarantee the first match is inserted.
278 // flat_hash_set::emplace()
280 // Inserts an element of the specified value by constructing it in-place
281 // within the `flat_hash_set`, provided that no element with the given key
284 // The element may be constructed even if there already is an element with the
285 // key in the container, in which case the newly constructed element will be
286 // destroyed immediately.
288 // If rehashing occurs due to the insertion, all iterators are invalidated.
291 // flat_hash_set::emplace_hint()
293 // Inserts an element of the specified value by constructing it in-place
294 // within the `flat_hash_set`, using the position of `hint` as a non-binding
295 // suggestion for where to begin the insertion search, and only inserts
296 // provided that no element with the given key already exists.
298 // The element may be constructed even if there already is an element with the
299 // key in the container, in which case the newly constructed element will be
300 // destroyed immediately.
302 // If rehashing occurs due to the insertion, all iterators are invalidated.
303 using Base::emplace_hint;
305 // flat_hash_set::extract()
307 // Extracts the indicated element, erasing it in the process, and returns it
308 // as a C++17-compatible node handle. Overloads are listed below.
310 // node_type extract(const_iterator position):
312 // Extracts the element at the indicated position and returns a node handle
313 // owning that extracted data.
315 // node_type extract(const key_type& x):
317 // Extracts the element with the key matching the passed key value and
318 // returns a node handle owning that extracted data. If the `flat_hash_set`
319 // does not contain an element with a matching key, this function returns an
320 // empty node handle.
323 // flat_hash_set::merge()
325 // Extracts elements from a given `source` flat hash map into this
326 // `flat_hash_set`. If the destination `flat_hash_set` already contains an
327 // element with an equivalent key, that element is not extracted.
330 // flat_hash_set::swap(flat_hash_set& other)
332 // Exchanges the contents of this `flat_hash_set` with those of the `other`
333 // flat hash map, avoiding invocation of any move, copy, or swap operations on
334 // individual elements.
336 // All iterators and references on the `flat_hash_set` remain valid, excepting
337 // for the past-the-end iterator, which is invalidated.
339 // `swap()` requires that the flat hash set's hashing and key equivalence
340 // functions be Swappable, and are exchaged using unqualified calls to
341 // non-member `swap()`. If the map's allocator has
342 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
343 // set to `true`, the allocators are also exchanged using an unqualified call
344 // to non-member `swap()`; otherwise, the allocators are not swapped.
347 // flat_hash_set::rehash(count)
349 // Rehashes the `flat_hash_set`, setting the number of slots to be at least
350 // the passed value. If the new number of slots increases the load factor more
351 // than the current maximum load factor
352 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
353 // will be at least `size()` / `max_load_factor()`.
355 // To force a rehash, pass rehash(0).
357 // NOTE: unlike behavior in `std::unordered_set`, references are also
358 // invalidated upon a `rehash()`.
361 // flat_hash_set::reserve(count)
363 // Sets the number of slots in the `flat_hash_set` to the number needed to
364 // accommodate at least `count` total elements without exceeding the current
365 // maximum load factor, and may rehash the container if needed.
368 // flat_hash_set::contains()
370 // Determines whether an element comparing equal to the given `key` exists
371 // within the `flat_hash_set`, returning `true` if so or `false` otherwise.
372 using Base::contains;
374 // flat_hash_set::count(const Key& key) const
376 // Returns the number of elements comparing equal to the given `key` within
377 // the `flat_hash_set`. note that this function will return either `1` or `0`
378 // since duplicate elements are not allowed within a `flat_hash_set`.
381 // flat_hash_set::equal_range()
383 // Returns a closed range [first, last], defined by a `std::pair` of two
384 // iterators, containing all elements with the passed key in the
386 using Base::equal_range;
388 // flat_hash_set::find()
390 // Finds an element with the passed `key` within the `flat_hash_set`.
393 // flat_hash_set::bucket_count()
395 // Returns the number of "buckets" within the `flat_hash_set`. Note that
396 // because a flat hash map contains all elements within its internal storage,
397 // this value simply equals the current capacity of the `flat_hash_set`.
398 using Base::bucket_count;
400 // flat_hash_set::load_factor()
402 // Returns the current load factor of the `flat_hash_set` (the average number
403 // of slots occupied with a value within the hash map).
404 using Base::load_factor;
406 // flat_hash_set::max_load_factor()
408 // Manages the maximum load factor of the `flat_hash_set`. Overloads are
411 // float flat_hash_set::max_load_factor()
413 // Returns the current maximum load factor of the `flat_hash_set`.
415 // void flat_hash_set::max_load_factor(float ml)
417 // Sets the maximum load factor of the `flat_hash_set` to the passed value.
419 // NOTE: This overload is provided only for API compatibility with the STL;
420 // `flat_hash_set` will ignore any set load factor and manage its rehashing
421 // internally as an implementation detail.
422 using Base::max_load_factor;
424 // flat_hash_set::get_allocator()
426 // Returns the allocator function associated with this `flat_hash_set`.
427 using Base::get_allocator;
429 // flat_hash_set::hash_function()
431 // Returns the hashing function used to hash the keys within this
433 using Base::hash_function;
435 // flat_hash_set::key_eq()
437 // Returns the function used for comparing keys equality.
441 namespace container_internal {
444 struct FlatHashSetPolicy {
448 using constant_iterators = std::true_type;
450 template <class Allocator, class... Args>
451 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
452 absl::allocator_traits<Allocator>::construct(*alloc, slot,
453 std::forward<Args>(args)...);
456 template <class Allocator>
457 static void destroy(Allocator* alloc, slot_type* slot) {
458 absl::allocator_traits<Allocator>::destroy(*alloc, slot);
461 template <class Allocator>
462 static void transfer(Allocator* alloc, slot_type* new_slot,
463 slot_type* old_slot) {
464 construct(alloc, new_slot, std::move(*old_slot));
465 destroy(alloc, old_slot);
468 static T& element(slot_type* slot) { return *slot; }
470 template <class F, class... Args>
471 static decltype(absl::container_internal::DecomposeValue(
472 std::declval<F>(), std::declval<Args>()...))
473 apply(F&& f, Args&&... args) {
474 return absl::container_internal::DecomposeValue(
475 std::forward<F>(f), std::forward<Args>(args)...);
478 static size_t space_used(const T*) { return 0; }
480 } // namespace container_internal
482 namespace container_algorithm_internal {
484 // Specialization of trait in absl/algorithm/container.h
485 template <class Key, class Hash, class KeyEqual, class Allocator>
486 struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>>
489 } // namespace container_algorithm_internal
493 #endif // ABSL_CONTAINER_FLAT_HASH_SET_H_