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_map.h
17 // -----------------------------------------------------------------------------
18 //
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.
26 //
27 // In most cases, your default choice for a hash map should be a map of type
28 // `flat_hash_map`.
29
30 #ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_
31 #define ABSL_CONTAINER_FLAT_HASH_MAP_H_
32
33 #include <cstddef>
34 #include <new>
35 #include <type_traits>
36 #include <utility>
37
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"
43
44 namespace absl {
45 ABSL_NAMESPACE_BEGIN
46 namespace container_internal {
47 template <class K, class V>
48 struct FlatHashMapPolicy;
49 } // namespace container_internal
50
51 // -----------------------------------------------------------------------------
52 // absl::flat_hash_map
53 // -----------------------------------------------------------------------------
54 //
55 // An `absl::flat_hash_map<K, V>` is an unordered associative container which
56 // has been optimized for both speed and memory footprint in most common use
57 // cases. Its interface is similar to that of `std::unordered_map<K, V>` with
58 // the following notable differences:
59 //
60 // * Requires keys that are CopyConstructible
61 // * Requires values that are MoveConstructible
62 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and
63 // `insert()`, provided that the map is provided a compatible heterogeneous
64 // hashing function and equality operator.
65 // * Invalidates any references and pointers to elements within the table after
66 // `rehash()`.
67 // * Contains a `capacity()` member function indicating the number of element
68 // slots (open, deleted, and empty) within the hash map.
69 // * Returns `void` from the `erase(iterator)` overload.
70 //
71 // By default, `flat_hash_map` uses the `absl::Hash` hashing framework.
72 // All fundamental and Abseil types that support the `absl::Hash` framework have
73 // a compatible equality operator for comparing insertions into `flat_hash_map`.
74 // If your type is not yet supported by the `absl::Hash` framework, see
75 // absl/hash/hash.h for information on extending Abseil hashing to user-defined
76 // types.
77 //
78 // NOTE: A `flat_hash_map` stores its value types directly inside its
79 // implementation array to avoid memory indirection. Because a `flat_hash_map`
80 // is designed to move data when rehashed, map values will not retain pointer
81 // stability. If you require pointer stability, or if your values are large,
82 // consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead.
83 // If your types are not moveable or you require pointer stability for keys,
84 // consider `absl::node_hash_map`.
85 //
86 // Example:
87 //
88 // // Create a flat hash map of three strings (that map to strings)
89 // absl::flat_hash_map<std::string, std::string> ducks =
90 // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
91 //
92 // // Insert a new element into the flat hash map
93 // ducks.insert({"d", "donald"});
94 //
95 // // Force a rehash of the flat hash map
96 // ducks.rehash(0);
97 //
98 // // Find the element with the key "b"
99 // std::string search_key = "b";
100 // auto result = ducks.find(search_key);
101 // if (result != ducks.end()) {
102 // std::cout << "Result: " << result->second << std::endl;
103 // }
104 template <class K, class V,
105 class Hash = absl::container_internal::hash_default_hash<K>,
106 class Eq = absl::container_internal::hash_default_eq<K>,
107 class Allocator = std::allocator<std::pair<const K, V>>>
108 class flat_hash_map : public absl::container_internal::raw_hash_map<
109 absl::container_internal::FlatHashMapPolicy<K, V>,
110 Hash, Eq, Allocator> {
111 using Base = typename flat_hash_map::raw_hash_map;
112
113 public:
114 // Constructors and Assignment Operators
115 //
116 // A flat_hash_map supports the same overload set as `std::unordered_map`
117 // for construction and assignment:
118 //
119 // * Default constructor
120 //
121 // // No allocation for the table's elements is made.
122 // absl::flat_hash_map<int, std::string> map1;
123 //
124 // * Initializer List constructor
125 //
126 // absl::flat_hash_map<int, std::string> map2 =
127 // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
128 //
129 // * Copy constructor
130 //
131 // absl::flat_hash_map<int, std::string> map3(map2);
132 //
133 // * Copy assignment operator
134 //
135 // // Hash functor and Comparator are copied as well
136 // absl::flat_hash_map<int, std::string> map4;
137 // map4 = map3;
138 //
139 // * Move constructor
140 //
141 // // Move is guaranteed efficient
142 // absl::flat_hash_map<int, std::string> map5(std::move(map4));
143 //
144 // * Move assignment operator
145 //
146 // // May be efficient if allocators are compatible
147 // absl::flat_hash_map<int, std::string> map6;
148 // map6 = std::move(map5);
149 //
150 // * Range constructor
151 //
152 // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
153 // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end());
flat_hash_map()154 flat_hash_map() {}
155 using Base::Base;
156
157 // flat_hash_map::begin()
158 //
159 // Returns an iterator to the beginning of the `flat_hash_map`.
160 using Base::begin;
161
162 // flat_hash_map::cbegin()
163 //
164 // Returns a const iterator to the beginning of the `flat_hash_map`.
165 using Base::cbegin;
166
167 // flat_hash_map::cend()
168 //
169 // Returns a const iterator to the end of the `flat_hash_map`.
170 using Base::cend;
171
172 // flat_hash_map::end()
173 //
174 // Returns an iterator to the end of the `flat_hash_map`.
175 using Base::end;
176
177 // flat_hash_map::capacity()
178 //
179 // Returns the number of element slots (assigned, deleted, and empty)
180 // available within the `flat_hash_map`.
181 //
182 // NOTE: this member function is particular to `absl::flat_hash_map` and is
183 // not provided in the `std::unordered_map` API.
184 using Base::capacity;
185
186 // flat_hash_map::empty()
187 //
188 // Returns whether or not the `flat_hash_map` is empty.
189 using Base::empty;
190
191 // flat_hash_map::max_size()
192 //
193 // Returns the largest theoretical possible number of elements within a
194 // `flat_hash_map` under current memory constraints. This value can be thought
195 // of the largest value of `std::distance(begin(), end())` for a
196 // `flat_hash_map<K, V>`.
197 using Base::max_size;
198
199 // flat_hash_map::size()
200 //
201 // Returns the number of elements currently within the `flat_hash_map`.
202 using Base::size;
203
204 // flat_hash_map::clear()
205 //
206 // Removes all elements from the `flat_hash_map`. Invalidates any references,
207 // pointers, or iterators referring to contained elements.
208 //
209 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
210 // the underlying buffer call `erase(begin(), end())`.
211 using Base::clear;
212
213 // flat_hash_map::erase()
214 //
215 // Erases elements within the `flat_hash_map`. Erasing does not trigger a
216 // rehash. Overloads are listed below.
217 //
218 // void erase(const_iterator pos):
219 //
220 // Erases the element at `position` of the `flat_hash_map`, returning
221 // `void`.
222 //
223 // NOTE: returning `void` in this case is different than that of STL
224 // containers in general and `std::unordered_map` in particular (which
225 // return an iterator to the element following the erased element). If that
226 // iterator is needed, simply post increment the iterator:
227 //
228 // map.erase(it++);
229 //
230 // iterator erase(const_iterator first, const_iterator last):
231 //
232 // Erases the elements in the open interval [`first`, `last`), returning an
233 // iterator pointing to `last`.
234 //
235 // size_type erase(const key_type& key):
236 //
237 // Erases the element with the matching key, if it exists.
238 using Base::erase;
239
240 // flat_hash_map::insert()
241 //
242 // Inserts an element of the specified value into the `flat_hash_map`,
243 // returning an iterator pointing to the newly inserted element, provided that
244 // an element with the given key does not already exist. If rehashing occurs
245 // due to the insertion, all iterators are invalidated. Overloads are listed
246 // below.
247 //
248 // std::pair<iterator,bool> insert(const init_type& value):
249 //
250 // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an
251 // iterator to the inserted element (or to the element that prevented the
252 // insertion) and a bool denoting whether the insertion took place.
253 //
254 // std::pair<iterator,bool> insert(T&& value):
255 // std::pair<iterator,bool> insert(init_type&& value):
256 //
257 // Inserts a moveable value into the `flat_hash_map`. Returns a pair
258 // consisting of an iterator to the inserted element (or to the element that
259 // prevented the insertion) and a bool denoting whether the insertion took
260 // place.
261 //
262 // iterator insert(const_iterator hint, const init_type& value):
263 // iterator insert(const_iterator hint, T&& value):
264 // iterator insert(const_iterator hint, init_type&& 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_map` we guarantee the
277 // first match is inserted.
278 //
279 // void insert(std::initializer_list<init_type> 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_map` we guarantee the first match is inserted.
286 using Base::insert;
287
288 // flat_hash_map::insert_or_assign()
289 //
290 // Inserts an element of the specified value into the `flat_hash_map` provided
291 // that a value with the given key does not already exist, or replaces it with
292 // the element value if a key for that value already exists, returning an
293 // iterator pointing to the newly inserted element. If rehashing occurs due
294 // to the insertion, all existing iterators are invalidated. Overloads are
295 // listed below.
296 //
297 // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
298 // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
299 //
300 // Inserts/Assigns (or moves) the element of the specified key into the
301 // `flat_hash_map`.
302 //
303 // iterator insert_or_assign(const_iterator hint,
304 // const init_type& k, T&& obj):
305 // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
306 //
307 // Inserts/Assigns (or moves) the element of the specified key into the
308 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
309 // for where to begin the insertion search.
310 using Base::insert_or_assign;
311
312 // flat_hash_map::emplace()
313 //
314 // Inserts an element of the specified value by constructing it in-place
315 // within the `flat_hash_map`, provided that no element with the given key
316 // already exists.
317 //
318 // The element may be constructed even if there already is an element with the
319 // key in the container, in which case the newly constructed element will be
320 // destroyed immediately. Prefer `try_emplace()` unless your key is not
321 // copyable or moveable.
322 //
323 // If rehashing occurs due to the insertion, all iterators are invalidated.
324 using Base::emplace;
325
326 // flat_hash_map::emplace_hint()
327 //
328 // Inserts an element of the specified value by constructing it in-place
329 // within the `flat_hash_map`, using the position of `hint` as a non-binding
330 // suggestion for where to begin the insertion search, and only inserts
331 // provided that no element with the given key already exists.
332 //
333 // The element may be constructed even if there already is an element with the
334 // key in the container, in which case the newly constructed element will be
335 // destroyed immediately. Prefer `try_emplace()` unless your key is not
336 // copyable or moveable.
337 //
338 // If rehashing occurs due to the insertion, all iterators are invalidated.
339 using Base::emplace_hint;
340
341 // flat_hash_map::try_emplace()
342 //
343 // Inserts an element of the specified value by constructing it in-place
344 // within the `flat_hash_map`, provided that no element with the given key
345 // already exists. Unlike `emplace()`, if an element with the given key
346 // already exists, we guarantee that no element is constructed.
347 //
348 // If rehashing occurs due to the insertion, all iterators are invalidated.
349 // Overloads are listed below.
350 //
351 // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
352 // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
353 //
354 // Inserts (via copy or move) the element of the specified key into the
355 // `flat_hash_map`.
356 //
357 // iterator try_emplace(const_iterator hint,
358 // const init_type& k, Args&&... args):
359 // iterator try_emplace(const_iterator hint, init_type&& k, Args&&... args):
360 //
361 // Inserts (via copy or move) the element of the specified key into the
362 // `flat_hash_map` using the position of `hint` as a non-binding suggestion
363 // for where to begin the insertion search.
364 //
365 // All `try_emplace()` overloads make the same guarantees regarding rvalue
366 // arguments as `std::unordered_map::try_emplace()`, namely that these
367 // functions will not move from rvalue arguments if insertions do not happen.
368 using Base::try_emplace;
369
370 // flat_hash_map::extract()
371 //
372 // Extracts the indicated element, erasing it in the process, and returns it
373 // as a C++17-compatible node handle. Overloads are listed below.
374 //
375 // node_type extract(const_iterator position):
376 //
377 // Extracts the key,value pair of the element at the indicated position and
378 // returns a node handle owning that extracted data.
379 //
380 // node_type extract(const key_type& x):
381 //
382 // Extracts the key,value pair of the element with a key matching the passed
383 // key value and returns a node handle owning that extracted data. If the
384 // `flat_hash_map` does not contain an element with a matching key, this
385 // function returns an empty node handle.
386 using Base::extract;
387
388 // flat_hash_map::merge()
389 //
390 // Extracts elements from a given `source` flat hash map into this
391 // `flat_hash_map`. If the destination `flat_hash_map` already contains an
392 // element with an equivalent key, that element is not extracted.
393 using Base::merge;
394
395 // flat_hash_map::swap(flat_hash_map& other)
396 //
397 // Exchanges the contents of this `flat_hash_map` with those of the `other`
398 // flat hash map, avoiding invocation of any move, copy, or swap operations on
399 // individual elements.
400 //
401 // All iterators and references on the `flat_hash_map` remain valid, excepting
402 // for the past-the-end iterator, which is invalidated.
403 //
404 // `swap()` requires that the flat hash map's hashing and key equivalence
405 // functions be Swappable, and are exchanged using unqualified calls to
406 // non-member `swap()`. If the map's allocator has
407 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
408 // set to `true`, the allocators are also exchanged using an unqualified call
409 // to non-member `swap()`; otherwise, the allocators are not swapped.
410 using Base::swap;
411
412 // flat_hash_map::rehash(count)
413 //
414 // Rehashes the `flat_hash_map`, setting the number of slots to be at least
415 // the passed value. If the new number of slots increases the load factor more
416 // than the current maximum load factor
417 // (`count` < `size()` / `max_load_factor()`), then the new number of slots
418 // will be at least `size()` / `max_load_factor()`.
419 //
420 // To force a rehash, pass rehash(0).
421 //
422 // NOTE: unlike behavior in `std::unordered_map`, references are also
423 // invalidated upon a `rehash()`.
424 using Base::rehash;
425
426 // flat_hash_map::reserve(count)
427 //
428 // Sets the number of slots in the `flat_hash_map` to the number needed to
429 // accommodate at least `count` total elements without exceeding the current
430 // maximum load factor, and may rehash the container if needed.
431 using Base::reserve;
432
433 // flat_hash_map::at()
434 //
435 // Returns a reference to the mapped value of the element with key equivalent
436 // to the passed key.
437 using Base::at;
438
439 // flat_hash_map::contains()
440 //
441 // Determines whether an element with a key comparing equal to the given `key`
442 // exists within the `flat_hash_map`, returning `true` if so or `false`
443 // otherwise.
444 using Base::contains;
445
446 // flat_hash_map::count(const Key& key) const
447 //
448 // Returns the number of elements with a key comparing equal to the given
449 // `key` within the `flat_hash_map`. note that this function will return
450 // either `1` or `0` since duplicate keys are not allowed within a
451 // `flat_hash_map`.
452 using Base::count;
453
454 // flat_hash_map::equal_range()
455 //
456 // Returns a closed range [first, last], defined by a `std::pair` of two
457 // iterators, containing all elements with the passed key in the
458 // `flat_hash_map`.
459 using Base::equal_range;
460
461 // flat_hash_map::find()
462 //
463 // Finds an element with the passed `key` within the `flat_hash_map`.
464 using Base::find;
465
466 // flat_hash_map::operator[]()
467 //
468 // Returns a reference to the value mapped to the passed key within the
469 // `flat_hash_map`, performing an `insert()` if the key does not already
470 // exist.
471 //
472 // If an insertion occurs and results in a rehashing of the container, all
473 // iterators are invalidated. Otherwise iterators are not affected and
474 // references are not invalidated. Overloads are listed below.
475 //
476 // T& operator[](const Key& key):
477 //
478 // Inserts an init_type object constructed in-place if the element with the
479 // given key does not exist.
480 //
481 // T& operator[](Key&& key):
482 //
483 // Inserts an init_type object constructed in-place provided that an element
484 // with the given key does not exist.
485 using Base::operator[];
486
487 // flat_hash_map::bucket_count()
488 //
489 // Returns the number of "buckets" within the `flat_hash_map`. Note that
490 // because a flat hash map contains all elements within its internal storage,
491 // this value simply equals the current capacity of the `flat_hash_map`.
492 using Base::bucket_count;
493
494 // flat_hash_map::load_factor()
495 //
496 // Returns the current load factor of the `flat_hash_map` (the average number
497 // of slots occupied with a value within the hash map).
498 using Base::load_factor;
499
500 // flat_hash_map::max_load_factor()
501 //
502 // Manages the maximum load factor of the `flat_hash_map`. Overloads are
503 // listed below.
504 //
505 // float flat_hash_map::max_load_factor()
506 //
507 // Returns the current maximum load factor of the `flat_hash_map`.
508 //
509 // void flat_hash_map::max_load_factor(float ml)
510 //
511 // Sets the maximum load factor of the `flat_hash_map` to the passed value.
512 //
513 // NOTE: This overload is provided only for API compatibility with the STL;
514 // `flat_hash_map` will ignore any set load factor and manage its rehashing
515 // internally as an implementation detail.
516 using Base::max_load_factor;
517
518 // flat_hash_map::get_allocator()
519 //
520 // Returns the allocator function associated with this `flat_hash_map`.
521 using Base::get_allocator;
522
523 // flat_hash_map::hash_function()
524 //
525 // Returns the hashing function used to hash the keys within this
526 // `flat_hash_map`.
527 using Base::hash_function;
528
529 // flat_hash_map::key_eq()
530 //
531 // Returns the function used for comparing keys equality.
532 using Base::key_eq;
533 };
534
535 // erase_if(flat_hash_map<>, Pred)
536 //
537 // Erases all elements that satisfy the predicate `pred` from the container `c`.
538 template <typename K, typename V, typename H, typename E, typename A,
539 typename Predicate>
erase_if(flat_hash_map<K,V,H,E,A> & c,Predicate pred)540 void erase_if(flat_hash_map<K, V, H, E, A>& c, Predicate pred) {
541 container_internal::EraseIf(pred, &c);
542 }
543
544 namespace container_internal {
545
546 template <class K, class V>
547 struct FlatHashMapPolicy {
548 using slot_policy = container_internal::map_slot_policy<K, V>;
549 using slot_type = typename slot_policy::slot_type;
550 using key_type = K;
551 using mapped_type = V;
552 using init_type = std::pair</*non const*/ key_type, mapped_type>;
553
554 template <class Allocator, class... Args>
constructFlatHashMapPolicy555 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
556 slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
557 }
558
559 template <class Allocator>
destroyFlatHashMapPolicy560 static void destroy(Allocator* alloc, slot_type* slot) {
561 slot_policy::destroy(alloc, slot);
562 }
563
564 template <class Allocator>
transferFlatHashMapPolicy565 static void transfer(Allocator* alloc, slot_type* new_slot,
566 slot_type* old_slot) {
567 slot_policy::transfer(alloc, new_slot, old_slot);
568 }
569
570 template <class F, class... Args>
decltypeFlatHashMapPolicy571 static decltype(absl::container_internal::DecomposePair(
572 std::declval<F>(), std::declval<Args>()...))
573 apply(F&& f, Args&&... args) {
574 return absl::container_internal::DecomposePair(std::forward<F>(f),
575 std::forward<Args>(args)...);
576 }
577
space_usedFlatHashMapPolicy578 static size_t space_used(const slot_type*) { return 0; }
579
elementFlatHashMapPolicy580 static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
581
valueFlatHashMapPolicy582 static V& value(std::pair<const K, V>* kv) { return kv->second; }
valueFlatHashMapPolicy583 static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
584 };
585
586 } // namespace container_internal
587
588 namespace container_algorithm_internal {
589
590 // Specialization of trait in absl/algorithm/container.h
591 template <class Key, class T, class Hash, class KeyEqual, class Allocator>
592 struct IsUnorderedContainer<
593 absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
594
595 } // namespace container_algorithm_internal
596
597 ABSL_NAMESPACE_END
598 } // namespace absl
599
600 #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_
601