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_map.h
17 // -----------------------------------------------------------------------------
19 // An `absl::flat_hash_map<K, V>` is an unordered associative container of
20 // unique keys and associated values designed to be a more efficient replacement
21 // for `std::unordered_map`. Like `unordered_map`, search, insertion, and
22 // deletion of map elements can be done as an `O(1)` operation. However,
23 // `flat_hash_map` (and other unordered associative containers known as the
24 // collection of Abseil "Swiss tables") contain other optimizations that result
25 // in both memory and computation advantages.
27 // In most cases, your default choice for a hash map should be a map of type
30 #ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_
31 #define ABSL_CONTAINER_FLAT_HASH_MAP_H_
35 #include <type_traits>
38 #include "absl/algorithm/container.h"
39 #include "absl/container/internal/container_memory.h"
40 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
41 #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
42 #include "absl/memory/memory.h"
45 namespace container_internal {
46 template <class K, class V>
47 struct FlatHashMapPolicy;
48 } // namespace container_internal
50 // -----------------------------------------------------------------------------
51 // absl::flat_hash_map
52 // -----------------------------------------------------------------------------
54 // An `absl::flat_hash_map<K, V>` is an unordered associative container which
55 // has been optimized for both speed and memory footprint in most common use
56 // cases. Its interface is similar to that of `std::unordered_map<K, V>` with
57 // the following notable differences:
59 // * Requires keys that are CopyConstructible
60 // * Requires values that are MoveConstructible
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 // * Invalidates any references and pointers to elements within the table after
66 // * Contains a `capacity()` member function indicating the number of element
67 // slots (open, deleted, and empty) within the hash map.
68 // * Returns `void` from the `erase(iterator)` overload.
70 // By default, `flat_hash_map` uses the `absl::Hash` hashing framework.
71 // All fundamental and Abseil types that support the `absl::Hash` framework have
72 // a compatible equality operator for comparing insertions into `flat_hash_map`.
73 // If your type is not yet supported by the `absl::Hash` framework, see
74 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
77 // NOTE: A `flat_hash_map` stores its value types directly inside its
78 // implementation array to avoid memory indirection. Because a `flat_hash_map`
79 // is designed to move data when rehashed, map values will not retain pointer
80 // stability. If you require pointer stability, or if your values are large,
81 // consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead.
82 // If your types are not moveable or you require pointer stability for keys,
83 // consider `absl::node_hash_map`.
87 // // Create a flat hash map of three strings (that map to strings)
88 // absl::flat_hash_map<std::string, std::string> ducks =
89 // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
91 // // Insert a new element into the flat hash map
92 // ducks.insert({"d", "donald"});
94 // // Force a rehash of the flat hash map
97 // // Find the element with the key "b"
98 // std::string search_key = "b";
99 // auto result = ducks.find(search_key);
100 // if (result != ducks.end()) {
101 // std::cout << "Result: " << result->second << std::endl;
103 template <class K, class V,
104 class Hash = absl::container_internal::hash_default_hash<K>,
105 class Eq = absl::container_internal::hash_default_eq<K>,
106 class Allocator = std::allocator<std::pair<const K, V>>>
107 class flat_hash_map : public absl::container_internal::raw_hash_map<
108 absl::container_internal::FlatHashMapPolicy<K, V>,
109 Hash, Eq, Allocator> {
110 using Base = typename flat_hash_map::raw_hash_map;
113 // Constructors and Assignment Operators
115 // A flat_hash_map supports the same overload set as `std::unordered_map`
116 // for construction and assignment:
118 // * Default constructor
120 // // No allocation for the table's elements is made.
121 // absl::flat_hash_map<int, std::string> map1;
123 // * Initializer List constructor
125 // absl::flat_hash_map<int, std::string> map2 =
126 // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
128 // * Copy constructor
130 // absl::flat_hash_map<int, std::string> map3(map2);
132 // * Copy assignment operator
134 // // Hash functor and Comparator are copied as well
135 // absl::flat_hash_map<int, std::string> map4;
138 // * Move constructor
140 // // Move is guaranteed efficient
141 // absl::flat_hash_map<int, std::string> map5(std::move(map4));
143 // * Move assignment operator
145 // // May be efficient if allocators are compatible
146 // absl::flat_hash_map<int, std::string> map6;
147 // map6 = std::move(map5);
149 // * Range constructor
151 // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
152 // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end());
156 // flat_hash_map::begin()
158 // Returns an iterator to the beginning of the `flat_hash_map`.
161 // flat_hash_map::cbegin()
163 // Returns a const iterator to the beginning of the `flat_hash_map`.
166 // flat_hash_map::cend()
168 // Returns a const iterator to the end of the `flat_hash_map`.
171 // flat_hash_map::end()
173 // Returns an iterator to the end of the `flat_hash_map`.
176 // flat_hash_map::capacity()
178 // Returns the number of element slots (assigned, deleted, and empty)
179 // available within the `flat_hash_map`.
181 // NOTE: this member function is particular to `absl::flat_hash_map` and is
182 // not provided in the `std::unordered_map` API.
183 using Base::capacity;
185 // flat_hash_map::empty()
187 // Returns whether or not the `flat_hash_map` is empty.
190 // flat_hash_map::max_size()
192 // Returns the largest theoretical possible number of elements within a
193 // `flat_hash_map` under current memory constraints. This value can be thought
194 // of the largest value of `std::distance(begin(), end())` for a
195 // `flat_hash_map<K, V>`.
196 using Base::max_size;
198 // flat_hash_map::size()
200 // Returns the number of elements currently within the `flat_hash_map`.
203 // flat_hash_map::clear()
205 // Removes all elements from the `flat_hash_map`. Invalidates any references,
206 // pointers, or iterators referring to contained elements.
208 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
209 // the underlying buffer call `erase(begin(), end())`.
212 // flat_hash_map::erase()
214 // Erases elements within the `flat_hash_map`. Erasing does not trigger a
215 // rehash. Overloads are listed below.
217 // void erase(const_iterator pos):
219 // Erases the element at `position` of the `flat_hash_map`, returning
222 // NOTE: returning `void` in this case is different than that of STL
223 // containers in general and `std::unordered_map` in particular (which
224 // return an iterator to the element following the erased element). If that
225 // iterator is needed, simply post increment the iterator:
229 // iterator erase(const_iterator first, const_iterator last):
231 // Erases the elements in the open interval [`first`, `last`), returning an
232 // iterator pointing to `last`.
234 // size_type erase(const key_type& key):
236 // Erases the element with the matching key, if it exists.
239 // flat_hash_map::insert()
241 // Inserts an element of the specified value into the `flat_hash_map`,
242 // returning an iterator pointing to the newly inserted element, provided that
243 // an element with the given key does not already exist. If rehashing occurs
244 // due to the insertion, all iterators are invalidated. Overloads are listed
247 // std::pair<iterator,bool> insert(const init_type& value):
249 // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an
250 // iterator to the inserted element (or to the element that prevented the
251 // insertion) and a bool denoting whether the insertion took place.
253 // std::pair<iterator,bool> insert(T&& value):
254 // std::pair<iterator,bool> insert(init_type&& value):
256 // Inserts a moveable value into the `flat_hash_map`. Returns a pair
257 // consisting of an iterator to the inserted element (or to the element that
258 // prevented the insertion) and a bool denoting whether the insertion took
261 // iterator insert(const_iterator hint, const init_type& value):
262 // iterator insert(const_iterator hint, T&& value):
263 // iterator insert(const_iterator hint, init_type&& value);
265 // Inserts a value, using the position of `hint` as a non-binding suggestion
266 // for where to begin the insertion search. Returns an iterator to the
267 // inserted element, or to the existing element that prevented the
270 // void insert(InputIterator first, InputIterator last):
272 // Inserts a range of values [`first`, `last`).
274 // NOTE: Although the STL does not specify which element may be inserted if
275 // multiple keys compare equivalently, for `flat_hash_map` we guarantee the
276 // first match is inserted.
278 // void insert(std::initializer_list<init_type> ilist):
280 // Inserts the elements within the initializer list `ilist`.
282 // NOTE: Although the STL does not specify which element may be inserted if
283 // multiple keys compare equivalently within the initializer list, for
284 // `flat_hash_map` we guarantee the first match is inserted.
287 // flat_hash_map::insert_or_assign()
289 // Inserts an element of the specified value into the `flat_hash_map` provided
290 // that a value with the given key does not already exist, or replaces it with
291 // the element value if a key for that value already exists, returning an
292 // iterator pointing to the newly inserted element. If rehashing occurs due
293 // to the insertion, all existing iterators are invalidated. Overloads are
296 // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
297 // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
299 // Inserts/Assigns (or moves) the element of the specified key into the
302 // iterator insert_or_assign(const_iterator hint,
303 // const init_type& k, T&& obj):
304 // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
306 // Inserts/Assigns (or moves) the element of the specified key into the
307 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
308 // for where to begin the insertion search.
309 using Base::insert_or_assign;
311 // flat_hash_map::emplace()
313 // Inserts an element of the specified value by constructing it in-place
314 // within the `flat_hash_map`, provided that no element with the given key
317 // The element may be constructed even if there already is an element with the
318 // key in the container, in which case the newly constructed element will be
319 // destroyed immediately. Prefer `try_emplace()` unless your key is not
320 // copyable or moveable.
322 // If rehashing occurs due to the insertion, all iterators are invalidated.
325 // flat_hash_map::emplace_hint()
327 // Inserts an element of the specified value by constructing it in-place
328 // within the `flat_hash_map`, using the position of `hint` as a non-binding
329 // suggestion for where to begin the insertion search, and only inserts
330 // provided that no element with the given key already exists.
332 // The element may be constructed even if there already is an element with the
333 // key in the container, in which case the newly constructed element will be
334 // destroyed immediately. Prefer `try_emplace()` unless your key is not
335 // copyable or moveable.
337 // If rehashing occurs due to the insertion, all iterators are invalidated.
338 using Base::emplace_hint;
340 // flat_hash_map::try_emplace()
342 // Inserts an element of the specified value by constructing it in-place
343 // within the `flat_hash_map`, provided that no element with the given key
344 // already exists. Unlike `emplace()`, if an element with the given key
345 // already exists, we guarantee that no element is constructed.
347 // If rehashing occurs due to the insertion, all iterators are invalidated.
348 // Overloads are listed below.
350 // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
351 // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
353 // Inserts (via copy or move) the element of the specified key into the
356 // iterator try_emplace(const_iterator hint,
357 // const init_type& k, Args&&... args):
358 // iterator try_emplace(const_iterator hint, init_type&& k, Args&&... args):
360 // Inserts (via copy or move) the element of the specified key into the
361 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
362 // for where to begin the insertion search.
363 using Base::try_emplace;
365 // flat_hash_map::extract()
367 // Extracts the indicated element, erasing it in the process, and returns it
368 // as a C++17-compatible node handle. Overloads are listed below.
370 // node_type extract(const_iterator position):
372 // Extracts the key,value pair of the element at the indicated position and
373 // returns a node handle owning that extracted data.
375 // node_type extract(const key_type& x):
377 // Extracts the key,value pair of the element with a key matching the passed
378 // key value and returns a node handle owning that extracted data. If the
379 // `flat_hash_map` does not contain an element with a matching key, this
380 // function returns an empty node handle.
383 // flat_hash_map::merge()
385 // Extracts elements from a given `source` flat hash map into this
386 // `flat_hash_map`. If the destination `flat_hash_map` already contains an
387 // element with an equivalent key, that element is not extracted.
390 // flat_hash_map::swap(flat_hash_map& other)
392 // Exchanges the contents of this `flat_hash_map` with those of the `other`
393 // flat hash map, avoiding invocation of any move, copy, or swap operations on
394 // individual elements.
396 // All iterators and references on the `flat_hash_map` remain valid, excepting
397 // for the past-the-end iterator, which is invalidated.
399 // `swap()` requires that the flat hash map's hashing and key equivalence
400 // functions be Swappable, and are exchaged using unqualified calls to
401 // non-member `swap()`. If the map's allocator has
402 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
403 // set to `true`, the allocators are also exchanged using an unqualified call
404 // to non-member `swap()`; otherwise, the allocators are not swapped.
407 // flat_hash_map::rehash(count)
409 // Rehashes the `flat_hash_map`, setting the number of slots to be at least
410 // the passed value. If the new number of slots increases the load factor more
411 // than the current maximum load factor
412 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
413 // will be at least `size()` / `max_load_factor()`.
415 // To force a rehash, pass rehash(0).
417 // NOTE: unlike behavior in `std::unordered_map`, references are also
418 // invalidated upon a `rehash()`.
421 // flat_hash_map::reserve(count)
423 // Sets the number of slots in the `flat_hash_map` to the number needed to
424 // accommodate at least `count` total elements without exceeding the current
425 // maximum load factor, and may rehash the container if needed.
428 // flat_hash_map::at()
430 // Returns a reference to the mapped value of the element with key equivalent
431 // to the passed key.
434 // flat_hash_map::contains()
436 // Determines whether an element with a key comparing equal to the given `key`
437 // exists within the `flat_hash_map`, returning `true` if so or `false`
439 using Base::contains;
441 // flat_hash_map::count(const Key& key) const
443 // Returns the number of elements with a key comparing equal to the given
444 // `key` within the `flat_hash_map`. note that this function will return
445 // either `1` or `0` since duplicate keys are not allowed within a
449 // flat_hash_map::equal_range()
451 // Returns a closed range [first, last], defined by a `std::pair` of two
452 // iterators, containing all elements with the passed key in the
454 using Base::equal_range;
456 // flat_hash_map::find()
458 // Finds an element with the passed `key` within the `flat_hash_map`.
461 // flat_hash_map::operator[]()
463 // Returns a reference to the value mapped to the passed key within the
464 // `flat_hash_map`, performing an `insert()` if the key does not already
467 // If an insertion occurs and results in a rehashing of the container, all
468 // iterators are invalidated. Otherwise iterators are not affected and
469 // references are not invalidated. Overloads are listed below.
471 // T& operator[](const Key& key):
473 // Inserts an init_type object constructed in-place if the element with the
474 // given key does not exist.
476 // T& operator[](Key&& key):
478 // Inserts an init_type object constructed in-place provided that an element
479 // with the given key does not exist.
480 using Base::operator[];
482 // flat_hash_map::bucket_count()
484 // Returns the number of "buckets" within the `flat_hash_map`. Note that
485 // because a flat hash map contains all elements within its internal storage,
486 // this value simply equals the current capacity of the `flat_hash_map`.
487 using Base::bucket_count;
489 // flat_hash_map::load_factor()
491 // Returns the current load factor of the `flat_hash_map` (the average number
492 // of slots occupied with a value within the hash map).
493 using Base::load_factor;
495 // flat_hash_map::max_load_factor()
497 // Manages the maximum load factor of the `flat_hash_map`. Overloads are
500 // float flat_hash_map::max_load_factor()
502 // Returns the current maximum load factor of the `flat_hash_map`.
504 // void flat_hash_map::max_load_factor(float ml)
506 // Sets the maximum load factor of the `flat_hash_map` to the passed value.
508 // NOTE: This overload is provided only for API compatibility with the STL;
509 // `flat_hash_map` will ignore any set load factor and manage its rehashing
510 // internally as an implementation detail.
511 using Base::max_load_factor;
513 // flat_hash_map::get_allocator()
515 // Returns the allocator function associated with this `flat_hash_map`.
516 using Base::get_allocator;
518 // flat_hash_map::hash_function()
520 // Returns the hashing function used to hash the keys within this
522 using Base::hash_function;
524 // flat_hash_map::key_eq()
526 // Returns the function used for comparing keys equality.
530 namespace container_internal {
532 template <class K, class V>
533 struct FlatHashMapPolicy {
534 using slot_policy = container_internal::map_slot_policy<K, V>;
535 using slot_type = typename slot_policy::slot_type;
537 using mapped_type = V;
538 using init_type = std::pair</*non const*/ key_type, mapped_type>;
540 template <class Allocator, class... Args>
541 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
542 slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
545 template <class Allocator>
546 static void destroy(Allocator* alloc, slot_type* slot) {
547 slot_policy::destroy(alloc, slot);
550 template <class Allocator>
551 static void transfer(Allocator* alloc, slot_type* new_slot,
552 slot_type* old_slot) {
553 slot_policy::transfer(alloc, new_slot, old_slot);
556 template <class F, class... Args>
557 static decltype(absl::container_internal::DecomposePair(
558 std::declval<F>(), std::declval<Args>()...))
559 apply(F&& f, Args&&... args) {
560 return absl::container_internal::DecomposePair(std::forward<F>(f),
561 std::forward<Args>(args)...);
564 static size_t space_used(const slot_type*) { return 0; }
566 static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
568 static V& value(std::pair<const K, V>* kv) { return kv->second; }
569 static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
572 } // namespace container_internal
574 namespace container_algorithm_internal {
576 // Specialization of trait in absl/algorithm/container.h
577 template <class Key, class T, class Hash, class KeyEqual, class Allocator>
578 struct IsUnorderedContainer<
579 absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
581 } // namespace container_algorithm_internal
585 #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_