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


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:19:57