00001 // Copyright 2018 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 // 00015 // ----------------------------------------------------------------------------- 00016 // File: flat_hash_map.h 00017 // ----------------------------------------------------------------------------- 00018 // 00019 // An `absl::flat_hash_map<K, V>` is an unordered associative container of 00020 // unique keys and associated values designed to be a more efficient replacement 00021 // for `std::unordered_map`. Like `unordered_map`, search, insertion, and 00022 // deletion of map elements can be done as an `O(1)` operation. However, 00023 // `flat_hash_map` (and other unordered associative containers known as the 00024 // collection of Abseil "Swiss tables") contain other optimizations that result 00025 // in both memory and computation advantages. 00026 // 00027 // In most cases, your default choice for a hash map should be a map of type 00028 // `flat_hash_map`. 00029 00030 #ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_ 00031 #define ABSL_CONTAINER_FLAT_HASH_MAP_H_ 00032 00033 #include <cstddef> 00034 #include <new> 00035 #include <type_traits> 00036 #include <utility> 00037 00038 #include "absl/algorithm/container.h" 00039 #include "absl/container/internal/container_memory.h" 00040 #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export 00041 #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export 00042 #include "absl/memory/memory.h" 00043 00044 namespace absl { 00045 namespace container_internal { 00046 template <class K, class V> 00047 struct FlatHashMapPolicy; 00048 } // namespace container_internal 00049 00050 // ----------------------------------------------------------------------------- 00051 // absl::flat_hash_map 00052 // ----------------------------------------------------------------------------- 00053 // 00054 // An `absl::flat_hash_map<K, V>` is an unordered associative container which 00055 // has been optimized for both speed and memory footprint in most common use 00056 // cases. Its interface is similar to that of `std::unordered_map<K, V>` with 00057 // the following notable differences: 00058 // 00059 // * Requires keys that are CopyConstructible 00060 // * Requires values that are MoveConstructible 00061 // * Supports heterogeneous lookup, through `find()`, `operator[]()` and 00062 // `insert()`, provided that the map is provided a compatible heterogeneous 00063 // hashing function and equality operator. 00064 // * Invalidates any references and pointers to elements within the table after 00065 // `rehash()`. 00066 // * Contains a `capacity()` member function indicating the number of element 00067 // slots (open, deleted, and empty) within the hash map. 00068 // * Returns `void` from the `erase(iterator)` overload. 00069 // 00070 // By default, `flat_hash_map` uses the `absl::Hash` hashing framework. 00071 // All fundamental and Abseil types that support the `absl::Hash` framework have 00072 // a compatible equality operator for comparing insertions into `flat_hash_map`. 00073 // If your type is not yet supported by the `absl::Hash` framework, see 00074 // absl/hash/hash.h for information on extending Abseil hashing to user-defined 00075 // types. 00076 // 00077 // NOTE: A `flat_hash_map` stores its value types directly inside its 00078 // implementation array to avoid memory indirection. Because a `flat_hash_map` 00079 // is designed to move data when rehashed, map values will not retain pointer 00080 // stability. If you require pointer stability, or your values are large, 00081 // consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead. 00082 // If your types are not moveable or you require pointer stability for keys, 00083 // consider `absl::node_hash_map`. 00084 // 00085 // Example: 00086 // 00087 // // Create a flat hash map of three strings (that map to strings) 00088 // absl::flat_hash_map<std::string, std::string> ducks = 00089 // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}}; 00090 // 00091 // // Insert a new element into the flat hash map 00092 // ducks.insert({"d", "donald"}); 00093 // 00094 // // Force a rehash of the flat hash map 00095 // ducks.rehash(0); 00096 // 00097 // // Find the element with the key "b" 00098 // std::string search_key = "b"; 00099 // auto result = ducks.find(search_key); 00100 // if (result != ducks.end()) { 00101 // std::cout << "Result: " << result->second << std::endl; 00102 // } 00103 template <class K, class V, 00104 class Hash = absl::container_internal::hash_default_hash<K>, 00105 class Eq = absl::container_internal::hash_default_eq<K>, 00106 class Allocator = std::allocator<std::pair<const K, V>>> 00107 class flat_hash_map : public absl::container_internal::raw_hash_map< 00108 absl::container_internal::FlatHashMapPolicy<K, V>, 00109 Hash, Eq, Allocator> { 00110 using Base = typename flat_hash_map::raw_hash_map; 00111 00112 public: 00113 // Constructors and Assignment Operators 00114 // 00115 // A flat_hash_map supports the same overload set as `std::unordered_map` 00116 // for construction and assignment: 00117 // 00118 // * Default constructor 00119 // 00120 // // No allocation for the table's elements is made. 00121 // absl::flat_hash_map<int, std::string> map1; 00122 // 00123 // * Initializer List constructor 00124 // 00125 // absl::flat_hash_map<int, std::string> map2 = 00126 // {{1, "huey"}, {2, "dewey"}, {3, "louie"},}; 00127 // 00128 // * Copy constructor 00129 // 00130 // absl::flat_hash_map<int, std::string> map3(map2); 00131 // 00132 // * Copy assignment operator 00133 // 00134 // // Hash functor and Comparator are copied as well 00135 // absl::flat_hash_map<int, std::string> map4; 00136 // map4 = map3; 00137 // 00138 // * Move constructor 00139 // 00140 // // Move is guaranteed efficient 00141 // absl::flat_hash_map<int, std::string> map5(std::move(map4)); 00142 // 00143 // * Move assignment operator 00144 // 00145 // // May be efficient if allocators are compatible 00146 // absl::flat_hash_map<int, std::string> map6; 00147 // map6 = std::move(map5); 00148 // 00149 // * Range constructor 00150 // 00151 // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}}; 00152 // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end()); 00153 flat_hash_map() {} 00154 using Base::Base; 00155 00156 // flat_hash_map::begin() 00157 // 00158 // Returns an iterator to the beginning of the `flat_hash_map`. 00159 using Base::begin; 00160 00161 // flat_hash_map::cbegin() 00162 // 00163 // Returns a const iterator to the beginning of the `flat_hash_map`. 00164 using Base::cbegin; 00165 00166 // flat_hash_map::cend() 00167 // 00168 // Returns a const iterator to the end of the `flat_hash_map`. 00169 using Base::cend; 00170 00171 // flat_hash_map::end() 00172 // 00173 // Returns an iterator to the end of the `flat_hash_map`. 00174 using Base::end; 00175 00176 // flat_hash_map::capacity() 00177 // 00178 // Returns the number of element slots (assigned, deleted, and empty) 00179 // available within the `flat_hash_map`. 00180 // 00181 // NOTE: this member function is particular to `absl::flat_hash_map` and is 00182 // not provided in the `std::unordered_map` API. 00183 using Base::capacity; 00184 00185 // flat_hash_map::empty() 00186 // 00187 // Returns whether or not the `flat_hash_map` is empty. 00188 using Base::empty; 00189 00190 // flat_hash_map::max_size() 00191 // 00192 // Returns the largest theoretical possible number of elements within a 00193 // `flat_hash_map` under current memory constraints. This value can be thought 00194 // of the largest value of `std::distance(begin(), end())` for a 00195 // `flat_hash_map<K, V>`. 00196 using Base::max_size; 00197 00198 // flat_hash_map::size() 00199 // 00200 // Returns the number of elements currently within the `flat_hash_map`. 00201 using Base::size; 00202 00203 // flat_hash_map::clear() 00204 // 00205 // Removes all elements from the `flat_hash_map`. Invalidates any references, 00206 // pointers, or iterators referring to contained elements. 00207 // 00208 // NOTE: this operation may shrink the underlying buffer. To avoid shrinking 00209 // the underlying buffer call `erase(begin(), end())`. 00210 using Base::clear; 00211 00212 // flat_hash_map::erase() 00213 // 00214 // Erases elements within the `flat_hash_map`. Erasing does not trigger a 00215 // rehash. Overloads are listed below. 00216 // 00217 // void erase(const_iterator pos): 00218 // 00219 // Erases the element at `position` of the `flat_hash_map`, returning 00220 // `void`. 00221 // 00222 // NOTE: returning `void` in this case is different than that of STL 00223 // containers in general and `std::unordered_map` in particular (which 00224 // return an iterator to the element following the erased element). If that 00225 // iterator is needed, simply post increment the iterator: 00226 // 00227 // map.erase(it++); 00228 // 00229 // iterator erase(const_iterator first, const_iterator last): 00230 // 00231 // Erases the elements in the open interval [`first`, `last`), returning an 00232 // iterator pointing to `last`. 00233 // 00234 // size_type erase(const key_type& key): 00235 // 00236 // Erases the element with the matching key, if it exists. 00237 using Base::erase; 00238 00239 // flat_hash_map::insert() 00240 // 00241 // Inserts an element of the specified value into the `flat_hash_map`, 00242 // returning an iterator pointing to the newly inserted element, provided that 00243 // an element with the given key does not already exist. If rehashing occurs 00244 // due to the insertion, all iterators are invalidated. Overloads are listed 00245 // below. 00246 // 00247 // std::pair<iterator,bool> insert(const init_type& value): 00248 // 00249 // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an 00250 // iterator to the inserted element (or to the element that prevented the 00251 // insertion) and a bool denoting whether the insertion took place. 00252 // 00253 // std::pair<iterator,bool> insert(T&& value): 00254 // std::pair<iterator,bool> insert(init_type&& value): 00255 // 00256 // Inserts a moveable value into the `flat_hash_map`. Returns a pair 00257 // consisting of an iterator to the inserted element (or to the element that 00258 // prevented the insertion) and a bool denoting whether the insertion took 00259 // place. 00260 // 00261 // iterator insert(const_iterator hint, const init_type& value): 00262 // iterator insert(const_iterator hint, T&& value): 00263 // iterator insert(const_iterator hint, init_type&& value); 00264 // 00265 // Inserts a value, using the position of `hint` as a non-binding suggestion 00266 // for where to begin the insertion search. Returns an iterator to the 00267 // inserted element, or to the existing element that prevented the 00268 // insertion. 00269 // 00270 // void insert(InputIterator first, InputIterator last): 00271 // 00272 // Inserts a range of values [`first`, `last`). 00273 // 00274 // NOTE: Although the STL does not specify which element may be inserted if 00275 // multiple keys compare equivalently, for `flat_hash_map` we guarantee the 00276 // first match is inserted. 00277 // 00278 // void insert(std::initializer_list<init_type> ilist): 00279 // 00280 // Inserts the elements within the initializer list `ilist`. 00281 // 00282 // NOTE: Although the STL does not specify which element may be inserted if 00283 // multiple keys compare equivalently within the initializer list, for 00284 // `flat_hash_map` we guarantee the first match is inserted. 00285 using Base::insert; 00286 00287 // flat_hash_map::insert_or_assign() 00288 // 00289 // Inserts an element of the specified value into the `flat_hash_map` provided 00290 // that a value with the given key does not already exist, or replaces it with 00291 // the element value if a key for that value already exists, returning an 00292 // iterator pointing to the newly inserted element. If rehashing occurs due 00293 // to the insertion, all existing iterators are invalidated. Overloads are 00294 // listed below. 00295 // 00296 // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj): 00297 // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj): 00298 // 00299 // Inserts/Assigns (or moves) the element of the specified key into the 00300 // `flat_hash_map`. 00301 // 00302 // iterator insert_or_assign(const_iterator hint, 00303 // const init_type& k, T&& obj): 00304 // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj): 00305 // 00306 // Inserts/Assigns (or moves) the element of the specified key into the 00307 // `flat_hash_map` using the position of `hint` as a non-binding suggestion 00308 // for where to begin the insertion search. 00309 using Base::insert_or_assign; 00310 00311 // flat_hash_map::emplace() 00312 // 00313 // Inserts an element of the specified value by constructing it in-place 00314 // within the `flat_hash_map`, provided that no element with the given key 00315 // already exists. 00316 // 00317 // The element may be constructed even if there already is an element with the 00318 // key in the container, in which case the newly constructed element will be 00319 // destroyed immediately. Prefer `try_emplace()` unless your key is not 00320 // copyable or moveable. 00321 // 00322 // If rehashing occurs due to the insertion, all iterators are invalidated. 00323 using Base::emplace; 00324 00325 // flat_hash_map::emplace_hint() 00326 // 00327 // Inserts an element of the specified value by constructing it in-place 00328 // within the `flat_hash_map`, using the position of `hint` as a non-binding 00329 // suggestion for where to begin the insertion search, and only inserts 00330 // provided that no element with the given key already exists. 00331 // 00332 // The element may be constructed even if there already is an element with the 00333 // key in the container, in which case the newly constructed element will be 00334 // destroyed immediately. Prefer `try_emplace()` unless your key is not 00335 // copyable or moveable. 00336 // 00337 // If rehashing occurs due to the insertion, all iterators are invalidated. 00338 using Base::emplace_hint; 00339 00340 // flat_hash_map::try_emplace() 00341 // 00342 // Inserts an element of the specified value by constructing it in-place 00343 // within the `flat_hash_map`, provided that no element with the given key 00344 // already exists. Unlike `emplace()`, if an element with the given key 00345 // already exists, we guarantee that no element is constructed. 00346 // 00347 // If rehashing occurs due to the insertion, all iterators are invalidated. 00348 // Overloads are listed below. 00349 // 00350 // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args): 00351 // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args): 00352 // 00353 // Inserts (via copy or move) the element of the specified key into the 00354 // `flat_hash_map`. 00355 // 00356 // iterator try_emplace(const_iterator hint, 00357 // const init_type& k, Args&&... args): 00358 // iterator try_emplace(const_iterator hint, init_type&& k, Args&&... args): 00359 // 00360 // Inserts (via copy or move) the element of the specified key into the 00361 // `flat_hash_map` using the position of `hint` as a non-binding suggestion 00362 // for where to begin the insertion search. 00363 using Base::try_emplace; 00364 00365 // flat_hash_map::extract() 00366 // 00367 // Extracts the indicated element, erasing it in the process, and returns it 00368 // as a C++17-compatible node handle. Overloads are listed below. 00369 // 00370 // node_type extract(const_iterator position): 00371 // 00372 // Extracts the key,value pair of the element at the indicated position and 00373 // returns a node handle owning that extracted data. 00374 // 00375 // node_type extract(const key_type& x): 00376 // 00377 // Extracts the key,value pair of the element with a key matching the passed 00378 // key value and returns a node handle owning that extracted data. If the 00379 // `flat_hash_map` does not contain an element with a matching key, this 00380 // function returns an empty node handle. 00381 using Base::extract; 00382 00383 // flat_hash_map::merge() 00384 // 00385 // Extracts elements from a given `source` flat hash map into this 00386 // `flat_hash_map`. If the destination `flat_hash_map` already contains an 00387 // element with an equivalent key, that element is not extracted. 00388 using Base::merge; 00389 00390 // flat_hash_map::swap(flat_hash_map& other) 00391 // 00392 // Exchanges the contents of this `flat_hash_map` with those of the `other` 00393 // flat hash map, avoiding invocation of any move, copy, or swap operations on 00394 // individual elements. 00395 // 00396 // All iterators and references on the `flat_hash_map` remain valid, excepting 00397 // for the past-the-end iterator, which is invalidated. 00398 // 00399 // `swap()` requires that the flat hash map's hashing and key equivalence 00400 // functions be Swappable, and are exchaged using unqualified calls to 00401 // non-member `swap()`. If the map's allocator has 00402 // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value` 00403 // set to `true`, the allocators are also exchanged using an unqualified call 00404 // to non-member `swap()`; otherwise, the allocators are not swapped. 00405 using Base::swap; 00406 00407 // flat_hash_map::rehash(count) 00408 // 00409 // Rehashes the `flat_hash_map`, setting the number of slots to be at least 00410 // the passed value. If the new number of slots increases the load factor more 00411 // than the current maximum load factor 00412 // (`count` < `size()` / `max_load_factor()`), then the new number of slots 00413 // will be at least `size()` / `max_load_factor()`. 00414 // 00415 // To force a rehash, pass rehash(0). 00416 // 00417 // NOTE: unlike behavior in `std::unordered_map`, references are also 00418 // invalidated upon a `rehash()`. 00419 using Base::rehash; 00420 00421 // flat_hash_map::reserve(count) 00422 // 00423 // Sets the number of slots in the `flat_hash_map` to the number needed to 00424 // accommodate at least `count` total elements without exceeding the current 00425 // maximum load factor, and may rehash the container if needed. 00426 using Base::reserve; 00427 00428 // flat_hash_map::at() 00429 // 00430 // Returns a reference to the mapped value of the element with key equivalent 00431 // to the passed key. 00432 using Base::at; 00433 00434 // flat_hash_map::contains() 00435 // 00436 // Determines whether an element with a key comparing equal to the given `key` 00437 // exists within the `flat_hash_map`, returning `true` if so or `false` 00438 // otherwise. 00439 using Base::contains; 00440 00441 // flat_hash_map::count(const Key& key) const 00442 // 00443 // Returns the number of elements with a key comparing equal to the given 00444 // `key` within the `flat_hash_map`. note that this function will return 00445 // either `1` or `0` since duplicate keys are not allowed within a 00446 // `flat_hash_map`. 00447 using Base::count; 00448 00449 // flat_hash_map::equal_range() 00450 // 00451 // Returns a closed range [first, last], defined by a `std::pair` of two 00452 // iterators, containing all elements with the passed key in the 00453 // `flat_hash_map`. 00454 using Base::equal_range; 00455 00456 // flat_hash_map::find() 00457 // 00458 // Finds an element with the passed `key` within the `flat_hash_map`. 00459 using Base::find; 00460 00461 // flat_hash_map::operator[]() 00462 // 00463 // Returns a reference to the value mapped to the passed key within the 00464 // `flat_hash_map`, performing an `insert()` if the key does not already 00465 // exist. 00466 // 00467 // If an insertion occurs and results in a rehashing of the container, all 00468 // iterators are invalidated. Otherwise iterators are not affected and 00469 // references are not invalidated. Overloads are listed below. 00470 // 00471 // T& operator[](const Key& key): 00472 // 00473 // Inserts an init_type object constructed in-place if the element with the 00474 // given key does not exist. 00475 // 00476 // T& operator[](Key&& key): 00477 // 00478 // Inserts an init_type object constructed in-place provided that an element 00479 // with the given key does not exist. 00480 using Base::operator[]; 00481 00482 // flat_hash_map::bucket_count() 00483 // 00484 // Returns the number of "buckets" within the `flat_hash_map`. Note that 00485 // because a flat hash map contains all elements within its internal storage, 00486 // this value simply equals the current capacity of the `flat_hash_map`. 00487 using Base::bucket_count; 00488 00489 // flat_hash_map::load_factor() 00490 // 00491 // Returns the current load factor of the `flat_hash_map` (the average number 00492 // of slots occupied with a value within the hash map). 00493 using Base::load_factor; 00494 00495 // flat_hash_map::max_load_factor() 00496 // 00497 // Manages the maximum load factor of the `flat_hash_map`. Overloads are 00498 // listed below. 00499 // 00500 // float flat_hash_map::max_load_factor() 00501 // 00502 // Returns the current maximum load factor of the `flat_hash_map`. 00503 // 00504 // void flat_hash_map::max_load_factor(float ml) 00505 // 00506 // Sets the maximum load factor of the `flat_hash_map` to the passed value. 00507 // 00508 // NOTE: This overload is provided only for API compatibility with the STL; 00509 // `flat_hash_map` will ignore any set load factor and manage its rehashing 00510 // internally as an implementation detail. 00511 using Base::max_load_factor; 00512 00513 // flat_hash_map::get_allocator() 00514 // 00515 // Returns the allocator function associated with this `flat_hash_map`. 00516 using Base::get_allocator; 00517 00518 // flat_hash_map::hash_function() 00519 // 00520 // Returns the hashing function used to hash the keys within this 00521 // `flat_hash_map`. 00522 using Base::hash_function; 00523 00524 // flat_hash_map::key_eq() 00525 // 00526 // Returns the function used for comparing keys equality. 00527 using Base::key_eq; 00528 }; 00529 00530 namespace container_internal { 00531 00532 template <class K, class V> 00533 struct FlatHashMapPolicy { 00534 using slot_policy = container_internal::map_slot_policy<K, V>; 00535 using slot_type = typename slot_policy::slot_type; 00536 using key_type = K; 00537 using mapped_type = V; 00538 using init_type = std::pair</*non const*/ key_type, mapped_type>; 00539 00540 template <class Allocator, class... Args> 00541 static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { 00542 slot_policy::construct(alloc, slot, std::forward<Args>(args)...); 00543 } 00544 00545 template <class Allocator> 00546 static void destroy(Allocator* alloc, slot_type* slot) { 00547 slot_policy::destroy(alloc, slot); 00548 } 00549 00550 template <class Allocator> 00551 static void transfer(Allocator* alloc, slot_type* new_slot, 00552 slot_type* old_slot) { 00553 slot_policy::transfer(alloc, new_slot, old_slot); 00554 } 00555 00556 template <class F, class... Args> 00557 static decltype(absl::container_internal::DecomposePair( 00558 std::declval<F>(), std::declval<Args>()...)) 00559 apply(F&& f, Args&&... args) { 00560 return absl::container_internal::DecomposePair(std::forward<F>(f), 00561 std::forward<Args>(args)...); 00562 } 00563 00564 static size_t space_used(const slot_type*) { return 0; } 00565 00566 static std::pair<const K, V>& element(slot_type* slot) { return slot->value; } 00567 00568 static V& value(std::pair<const K, V>* kv) { return kv->second; } 00569 static const V& value(const std::pair<const K, V>* kv) { return kv->second; } 00570 }; 00571 00572 } // namespace container_internal 00573 00574 namespace container_algorithm_internal { 00575 00576 // Specialization of trait in absl/algorithm/container.h 00577 template <class Key, class T, class Hash, class KeyEqual, class Allocator> 00578 struct IsUnorderedContainer< 00579 absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; 00580 00581 } // namespace container_algorithm_internal 00582 00583 } // namespace absl 00584 00585 #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_