flat_hash_map.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: 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 
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 namespace container_internal {
46 template <class K, class V>
48 } // namespace container_internal
49 
50 // -----------------------------------------------------------------------------
51 // absl::flat_hash_map
52 // -----------------------------------------------------------------------------
53 //
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:
58 //
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
65 // `rehash()`.
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.
69 //
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
75 // types.
76 //
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 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`.
84 //
85 // Example:
86 //
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"}};
90 //
91 // // Insert a new element into the flat hash map
92 // ducks.insert({"d", "donald"});
93 //
94 // // Force a rehash of the flat hash map
95 // ducks.rehash(0);
96 //
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;
102 // }
103 template <class K, class V,
106  class Allocator = std::allocator<std::pair<const K, V>>>
108  absl::container_internal::FlatHashMapPolicy<K, V>,
109  Hash, Eq, Allocator> {
111 
112  public:
113  // Constructors and Assignment Operators
114  //
115  // A flat_hash_map supports the same overload set as `std::unordered_map`
116  // for construction and assignment:
117  //
118  // * Default constructor
119  //
120  // // No allocation for the table's elements is made.
121  // absl::flat_hash_map<int, std::string> map1;
122  //
123  // * Initializer List constructor
124  //
125  // absl::flat_hash_map<int, std::string> map2 =
126  // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
127  //
128  // * Copy constructor
129  //
130  // absl::flat_hash_map<int, std::string> map3(map2);
131  //
132  // * Copy assignment operator
133  //
134  // // Hash functor and Comparator are copied as well
135  // absl::flat_hash_map<int, std::string> map4;
136  // map4 = map3;
137  //
138  // * Move constructor
139  //
140  // // Move is guaranteed efficient
141  // absl::flat_hash_map<int, std::string> map5(std::move(map4));
142  //
143  // * Move assignment operator
144  //
145  // // May be efficient if allocators are compatible
146  // absl::flat_hash_map<int, std::string> map6;
147  // map6 = std::move(map5);
148  //
149  // * Range constructor
150  //
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());
154  using Base::Base;
155 
156  // flat_hash_map::begin()
157  //
158  // Returns an iterator to the beginning of the `flat_hash_map`.
159  using Base::begin;
160 
161  // flat_hash_map::cbegin()
162  //
163  // Returns a const iterator to the beginning of the `flat_hash_map`.
164  using Base::cbegin;
165 
166  // flat_hash_map::cend()
167  //
168  // Returns a const iterator to the end of the `flat_hash_map`.
169  using Base::cend;
170 
171  // flat_hash_map::end()
172  //
173  // Returns an iterator to the end of the `flat_hash_map`.
174  using Base::end;
175 
176  // flat_hash_map::capacity()
177  //
178  // Returns the number of element slots (assigned, deleted, and empty)
179  // available within the `flat_hash_map`.
180  //
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;
184 
185  // flat_hash_map::empty()
186  //
187  // Returns whether or not the `flat_hash_map` is empty.
188  using Base::empty;
189 
190  // flat_hash_map::max_size()
191  //
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;
197 
198  // flat_hash_map::size()
199  //
200  // Returns the number of elements currently within the `flat_hash_map`.
201  using Base::size;
202 
203  // flat_hash_map::clear()
204  //
205  // Removes all elements from the `flat_hash_map`. Invalidates any references,
206  // pointers, or iterators referring to contained elements.
207  //
208  // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
209  // the underlying buffer call `erase(begin(), end())`.
210  using Base::clear;
211 
212  // flat_hash_map::erase()
213  //
214  // Erases elements within the `flat_hash_map`. Erasing does not trigger a
215  // rehash. Overloads are listed below.
216  //
217  // void erase(const_iterator pos):
218  //
219  // Erases the element at `position` of the `flat_hash_map`, returning
220  // `void`.
221  //
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:
226  //
227  // map.erase(it++);
228  //
229  // iterator erase(const_iterator first, const_iterator last):
230  //
231  // Erases the elements in the open interval [`first`, `last`), returning an
232  // iterator pointing to `last`.
233  //
234  // size_type erase(const key_type& key):
235  //
236  // Erases the element with the matching key, if it exists.
237  using Base::erase;
238 
239  // flat_hash_map::insert()
240  //
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
245  // below.
246  //
247  // std::pair<iterator,bool> insert(const init_type& value):
248  //
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.
252  //
253  // std::pair<iterator,bool> insert(T&& value):
254  // std::pair<iterator,bool> insert(init_type&& value):
255  //
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
259  // place.
260  //
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);
264  //
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
268  // insertion.
269  //
270  // void insert(InputIterator first, InputIterator last):
271  //
272  // Inserts a range of values [`first`, `last`).
273  //
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.
277  //
278  // void insert(std::initializer_list<init_type> ilist):
279  //
280  // Inserts the elements within the initializer list `ilist`.
281  //
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.
285  using Base::insert;
286 
287  // flat_hash_map::insert_or_assign()
288  //
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
294  // listed below.
295  //
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):
298  //
299  // Inserts/Assigns (or moves) the element of the specified key into the
300  // `flat_hash_map`.
301  //
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):
305  //
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;
310 
311  // flat_hash_map::emplace()
312  //
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
315  // already exists.
316  //
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.
321  //
322  // If rehashing occurs due to the insertion, all iterators are invalidated.
323  using Base::emplace;
324 
325  // flat_hash_map::emplace_hint()
326  //
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.
331  //
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.
336  //
337  // If rehashing occurs due to the insertion, all iterators are invalidated.
338  using Base::emplace_hint;
339 
340  // flat_hash_map::try_emplace()
341  //
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.
346  //
347  // If rehashing occurs due to the insertion, all iterators are invalidated.
348  // Overloads are listed below.
349  //
350  // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
351  // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
352  //
353  // Inserts (via copy or move) the element of the specified key into the
354  // `flat_hash_map`.
355  //
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):
359  //
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;
364 
365  // flat_hash_map::extract()
366  //
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.
369  //
370  // node_type extract(const_iterator position):
371  //
372  // Extracts the key,value pair of the element at the indicated position and
373  // returns a node handle owning that extracted data.
374  //
375  // node_type extract(const key_type& x):
376  //
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.
381  using Base::extract;
382 
383  // flat_hash_map::merge()
384  //
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.
388  using Base::merge;
389 
390  // flat_hash_map::swap(flat_hash_map& other)
391  //
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.
395  //
396  // All iterators and references on the `flat_hash_map` remain valid, excepting
397  // for the past-the-end iterator, which is invalidated.
398  //
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.
405  using Base::swap;
406 
407  // flat_hash_map::rehash(count)
408  //
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()`.
414  //
415  // To force a rehash, pass rehash(0).
416  //
417  // NOTE: unlike behavior in `std::unordered_map`, references are also
418  // invalidated upon a `rehash()`.
419  using Base::rehash;
420 
421  // flat_hash_map::reserve(count)
422  //
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.
426  using Base::reserve;
427 
428  // flat_hash_map::at()
429  //
430  // Returns a reference to the mapped value of the element with key equivalent
431  // to the passed key.
432  using Base::at;
433 
434  // flat_hash_map::contains()
435  //
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`
438  // otherwise.
439  using Base::contains;
440 
441  // flat_hash_map::count(const Key& key) const
442  //
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
446  // `flat_hash_map`.
447  using Base::count;
448 
449  // flat_hash_map::equal_range()
450  //
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
453  // `flat_hash_map`.
454  using Base::equal_range;
455 
456  // flat_hash_map::find()
457  //
458  // Finds an element with the passed `key` within the `flat_hash_map`.
459  using Base::find;
460 
461  // flat_hash_map::operator[]()
462  //
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
465  // exist.
466  //
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.
470  //
471  // T& operator[](const Key& key):
472  //
473  // Inserts an init_type object constructed in-place if the element with the
474  // given key does not exist.
475  //
476  // T& operator[](Key&& key):
477  //
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[];
481 
482  // flat_hash_map::bucket_count()
483  //
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;
488 
489  // flat_hash_map::load_factor()
490  //
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;
494 
495  // flat_hash_map::max_load_factor()
496  //
497  // Manages the maximum load factor of the `flat_hash_map`. Overloads are
498  // listed below.
499  //
500  // float flat_hash_map::max_load_factor()
501  //
502  // Returns the current maximum load factor of the `flat_hash_map`.
503  //
504  // void flat_hash_map::max_load_factor(float ml)
505  //
506  // Sets the maximum load factor of the `flat_hash_map` to the passed value.
507  //
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;
512 
513  // flat_hash_map::get_allocator()
514  //
515  // Returns the allocator function associated with this `flat_hash_map`.
516  using Base::get_allocator;
517 
518  // flat_hash_map::hash_function()
519  //
520  // Returns the hashing function used to hash the keys within this
521  // `flat_hash_map`.
522  using Base::hash_function;
523 
524  // flat_hash_map::key_eq()
525  //
526  // Returns the function used for comparing keys equality.
527  using Base::key_eq;
528 };
529 
530 namespace container_internal {
531 
532 template <class K, class V>
533 struct FlatHashMapPolicy {
536  using key_type = K;
537  using mapped_type = V;
538  using init_type = std::pair</*non const*/ key_type, mapped_type>;
539 
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)...);
543  }
544 
545  template <class Allocator>
546  static void destroy(Allocator* alloc, slot_type* slot) {
547  slot_policy::destroy(alloc, slot);
548  }
549 
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);
554  }
555 
556  template <class F, class... Args>
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)...);
562  }
563 
564  static size_t space_used(const slot_type*) { return 0; }
565 
566  static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
567 
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; }
570 };
571 
572 } // namespace container_internal
573 
574 namespace container_algorithm_internal {
575 
576 // Specialization of trait in absl/algorithm/container.h
577 template <class Key, class T, class Hash, class KeyEqual, class Allocator>
579  absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
580 
581 } // namespace container_algorithm_internal
582 
583 } // namespace absl
584 
585 #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_
static std::pair< const K, V > & element(slot_type *slot)
hash_default_eq< T > key_eq
std::pair< key_type, mapped_type > init_type
char * begin
typename container_internal::HashEq< T >::Hash hash_default_hash
static V & value(std::pair< const K, V > *kv)
char * end
Definition: algorithm.h:29
static std::function< void(void *, Slot *)> destroy
static void destroy(Allocator *alloc, slot_type *slot)
static void transfer(Allocator *alloc, slot_type *new_slot, slot_type *old_slot)
typename flat_hash_map::raw_hash_map Base
typename slot_policy::slot_type slot_type
std::pair< std::string, std::string > pair
void swap(absl::InlinedVector< T, N, A > &a, absl::InlinedVector< T, N, A > &b) noexcept(noexcept(a.swap(b)))
auto DecomposePair(F &&f, Args &&...args) -> decltype(memory_internal::DecomposePairImpl(std::forward< F >(f), PairArgs(std::forward< Args >(args)...)))
static std::function< void(void *, Slot *, Slot *)> transfer
static std::function< void(void *, Slot *, Slot)> construct
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
static size_t space_used(const slot_type *)
uintptr_t size
static const V & value(const std::pair< const K, V > *kv)
typename container_internal::HashEq< T >::Eq hash_default_eq
std::allocator< int > alloc
static void construct(Allocator *alloc, slot_type *slot, Args &&...args)
absl::hash_internal::Hash< T > Hash
Definition: hash.h:213


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