flat_hash_map.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. // `flat_hash_map` is not exception-safe.
  31. #ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_
  32. #define ABSL_CONTAINER_FLAT_HASH_MAP_H_
  33. #include <cstddef>
  34. #include <memory>
  35. #include <type_traits>
  36. #include <utility>
  37. #include "absl/algorithm/container.h"
  38. #include "absl/base/attributes.h"
  39. #include "absl/base/macros.h"
  40. #include "absl/container/hash_container_defaults.h"
  41. #include "absl/container/internal/container_memory.h"
  42. #include "absl/container/internal/raw_hash_map.h" // IWYU pragma: export
  43. #include "absl/meta/type_traits.h"
  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. // 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. See below for details.
  64. // * Invalidates any references and pointers to elements within the table after
  65. // `rehash()` and when the table is moved.
  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. // Using `absl::flat_hash_map` at interface boundaries in dynamically loaded
  78. // libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
  79. // be randomized across dynamically loaded libraries.
  80. //
  81. // To achieve heterogeneous lookup for custom types either `Hash` and `Eq` type
  82. // parameters can be used or `T` should have public inner types
  83. // `absl_container_hash` and (optionally) `absl_container_eq`. In either case,
  84. // `typename Hash::is_transparent` and `typename Eq::is_transparent` should be
  85. // well-formed. Both types are basically functors:
  86. // * `Hash` should support `size_t operator()(U val) const` that returns a hash
  87. // for the given `val`.
  88. // * `Eq` should support `bool operator()(U lhs, V rhs) const` that returns true
  89. // if `lhs` is equal to `rhs`.
  90. //
  91. // In most cases `T` needs only to provide the `absl_container_hash`. In this
  92. // case `std::equal_to<void>` will be used instead of `eq` part.
  93. //
  94. // NOTE: A `flat_hash_map` stores its value types directly inside its
  95. // implementation array to avoid memory indirection. Because a `flat_hash_map`
  96. // is designed to move data when rehashed, map values will not retain pointer
  97. // stability. If you require pointer stability, or if your values are large,
  98. // consider using `absl::flat_hash_map<Key, std::unique_ptr<Value>>` instead.
  99. // If your types are not moveable or you require pointer stability for keys,
  100. // consider `absl::node_hash_map`.
  101. //
  102. // Example:
  103. //
  104. // // Create a flat hash map of three strings (that map to strings)
  105. // absl::flat_hash_map<std::string, std::string> ducks =
  106. // {{"a", "huey"}, {"b", "dewey"}, {"c", "louie"}};
  107. //
  108. // // Insert a new element into the flat hash map
  109. // ducks.insert({"d", "donald"});
  110. //
  111. // // Force a rehash of the flat hash map
  112. // ducks.rehash(0);
  113. //
  114. // // Find the element with the key "b"
  115. // std::string search_key = "b";
  116. // auto result = ducks.find(search_key);
  117. // if (result != ducks.end()) {
  118. // std::cout << "Result: " << result->second << std::endl;
  119. // }
  120. template <class K, class V, class Hash = DefaultHashContainerHash<K>,
  121. class Eq = DefaultHashContainerEq<K>,
  122. class Allocator = std::allocator<std::pair<const K, V>>>
  123. class ABSL_ATTRIBUTE_OWNER flat_hash_map
  124. : public absl::container_internal::raw_hash_map<
  125. absl::container_internal::FlatHashMapPolicy<K, V>, Hash, Eq,
  126. Allocator> {
  127. using Base = typename flat_hash_map::raw_hash_map;
  128. public:
  129. // Constructors and Assignment Operators
  130. //
  131. // A flat_hash_map supports the same overload set as `std::unordered_map`
  132. // for construction and assignment:
  133. //
  134. // * Default constructor
  135. //
  136. // // No allocation for the table's elements is made.
  137. // absl::flat_hash_map<int, std::string> map1;
  138. //
  139. // * Initializer List constructor
  140. //
  141. // absl::flat_hash_map<int, std::string> map2 =
  142. // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
  143. //
  144. // * Copy constructor
  145. //
  146. // absl::flat_hash_map<int, std::string> map3(map2);
  147. //
  148. // * Copy assignment operator
  149. //
  150. // // Hash functor and Comparator are copied as well
  151. // absl::flat_hash_map<int, std::string> map4;
  152. // map4 = map3;
  153. //
  154. // * Move constructor
  155. //
  156. // // Move is guaranteed efficient
  157. // absl::flat_hash_map<int, std::string> map5(std::move(map4));
  158. //
  159. // * Move assignment operator
  160. //
  161. // // May be efficient if allocators are compatible
  162. // absl::flat_hash_map<int, std::string> map6;
  163. // map6 = std::move(map5);
  164. //
  165. // * Range constructor
  166. //
  167. // std::vector<std::pair<int, std::string>> v = {{1, "a"}, {2, "b"}};
  168. // absl::flat_hash_map<int, std::string> map7(v.begin(), v.end());
  169. flat_hash_map() {}
  170. using Base::Base;
  171. // flat_hash_map::begin()
  172. //
  173. // Returns an iterator to the beginning of the `flat_hash_map`.
  174. using Base::begin;
  175. // flat_hash_map::cbegin()
  176. //
  177. // Returns a const iterator to the beginning of the `flat_hash_map`.
  178. using Base::cbegin;
  179. // flat_hash_map::cend()
  180. //
  181. // Returns a const iterator to the end of the `flat_hash_map`.
  182. using Base::cend;
  183. // flat_hash_map::end()
  184. //
  185. // Returns an iterator to the end of the `flat_hash_map`.
  186. using Base::end;
  187. // flat_hash_map::capacity()
  188. //
  189. // Returns the number of element slots (assigned, deleted, and empty)
  190. // available within the `flat_hash_map`.
  191. //
  192. // NOTE: this member function is particular to `absl::flat_hash_map` and is
  193. // not provided in the `std::unordered_map` API.
  194. using Base::capacity;
  195. // flat_hash_map::empty()
  196. //
  197. // Returns whether or not the `flat_hash_map` is empty.
  198. using Base::empty;
  199. // flat_hash_map::max_size()
  200. //
  201. // Returns the largest theoretical possible number of elements within a
  202. // `flat_hash_map` under current memory constraints. This value can be thought
  203. // of the largest value of `std::distance(begin(), end())` for a
  204. // `flat_hash_map<K, V>`.
  205. using Base::max_size;
  206. // flat_hash_map::size()
  207. //
  208. // Returns the number of elements currently within the `flat_hash_map`.
  209. using Base::size;
  210. // flat_hash_map::clear()
  211. //
  212. // Removes all elements from the `flat_hash_map`. Invalidates any references,
  213. // pointers, or iterators referring to contained elements.
  214. //
  215. // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
  216. // the underlying buffer call `erase(begin(), end())`.
  217. using Base::clear;
  218. // flat_hash_map::erase()
  219. //
  220. // Erases elements within the `flat_hash_map`. Erasing does not trigger a
  221. // rehash. Overloads are listed below.
  222. //
  223. // void erase(const_iterator pos):
  224. //
  225. // Erases the element at `position` of the `flat_hash_map`, returning
  226. // `void`.
  227. //
  228. // NOTE: returning `void` in this case is different than that of STL
  229. // containers in general and `std::unordered_map` in particular (which
  230. // return an iterator to the element following the erased element). If that
  231. // iterator is needed, simply post increment the iterator:
  232. //
  233. // map.erase(it++);
  234. //
  235. // iterator erase(const_iterator first, const_iterator last):
  236. //
  237. // Erases the elements in the open interval [`first`, `last`), returning an
  238. // iterator pointing to `last`. The special case of calling
  239. // `erase(begin(), end())` resets the reserved growth such that if
  240. // `reserve(N)` has previously been called and there has been no intervening
  241. // call to `clear()`, then after calling `erase(begin(), end())`, it is safe
  242. // to assume that inserting N elements will not cause a rehash.
  243. //
  244. // size_type erase(const key_type& key):
  245. //
  246. // Erases the element with the matching key, if it exists, returning the
  247. // number of elements erased (0 or 1).
  248. using Base::erase;
  249. // flat_hash_map::insert()
  250. //
  251. // Inserts an element of the specified value into the `flat_hash_map`,
  252. // returning an iterator pointing to the newly inserted element, provided that
  253. // an element with the given key does not already exist. If rehashing occurs
  254. // due to the insertion, all iterators are invalidated. Overloads are listed
  255. // below.
  256. //
  257. // std::pair<iterator,bool> insert(const init_type& value):
  258. //
  259. // Inserts a value into the `flat_hash_map`. Returns a pair consisting of an
  260. // iterator to the inserted element (or to the element that prevented the
  261. // insertion) and a bool denoting whether the insertion took place.
  262. //
  263. // std::pair<iterator,bool> insert(T&& value):
  264. // std::pair<iterator,bool> insert(init_type&& value):
  265. //
  266. // Inserts a moveable value into the `flat_hash_map`. Returns a pair
  267. // consisting of an iterator to the inserted element (or to the element that
  268. // prevented the insertion) and a bool denoting whether the insertion took
  269. // place.
  270. //
  271. // iterator insert(const_iterator hint, const init_type& value):
  272. // iterator insert(const_iterator hint, T&& value):
  273. // iterator insert(const_iterator hint, init_type&& value);
  274. //
  275. // Inserts a value, using the position of `hint` as a non-binding suggestion
  276. // for where to begin the insertion search. Returns an iterator to the
  277. // inserted element, or to the existing element that prevented the
  278. // insertion.
  279. //
  280. // void insert(InputIterator first, InputIterator last):
  281. //
  282. // Inserts a range of values [`first`, `last`).
  283. //
  284. // NOTE: Although the STL does not specify which element may be inserted if
  285. // multiple keys compare equivalently, for `flat_hash_map` we guarantee the
  286. // first match is inserted.
  287. //
  288. // void insert(std::initializer_list<init_type> ilist):
  289. //
  290. // Inserts the elements within the initializer list `ilist`.
  291. //
  292. // NOTE: Although the STL does not specify which element may be inserted if
  293. // multiple keys compare equivalently within the initializer list, for
  294. // `flat_hash_map` we guarantee the first match is inserted.
  295. using Base::insert;
  296. // flat_hash_map::insert_or_assign()
  297. //
  298. // Inserts an element of the specified value into the `flat_hash_map` provided
  299. // that a value with the given key does not already exist, or replaces it with
  300. // the element value if a key for that value already exists, returning an
  301. // iterator pointing to the newly inserted element. If rehashing occurs due
  302. // to the insertion, all existing iterators are invalidated. Overloads are
  303. // listed below.
  304. //
  305. // pair<iterator, bool> insert_or_assign(const init_type& k, T&& obj):
  306. // pair<iterator, bool> insert_or_assign(init_type&& k, T&& obj):
  307. //
  308. // Inserts/Assigns (or moves) the element of the specified key into the
  309. // `flat_hash_map`.
  310. //
  311. // iterator insert_or_assign(const_iterator hint,
  312. // const init_type& k, T&& obj):
  313. // iterator insert_or_assign(const_iterator hint, init_type&& k, T&& obj):
  314. //
  315. // Inserts/Assigns (or moves) the element of the specified key into the
  316. // `flat_hash_map` using the position of `hint` as a non-binding suggestion
  317. // for where to begin the insertion search.
  318. using Base::insert_or_assign;
  319. // flat_hash_map::emplace()
  320. //
  321. // Inserts an element of the specified value by constructing it in-place
  322. // within the `flat_hash_map`, provided that no element with the given key
  323. // already exists.
  324. //
  325. // The element may be constructed even if there already is an element with the
  326. // key in the container, in which case the newly constructed element will be
  327. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  328. // copyable or moveable.
  329. //
  330. // If rehashing occurs due to the insertion, all iterators are invalidated.
  331. using Base::emplace;
  332. // flat_hash_map::emplace_hint()
  333. //
  334. // Inserts an element of the specified value by constructing it in-place
  335. // within the `flat_hash_map`, using the position of `hint` as a non-binding
  336. // suggestion for where to begin the insertion search, and only inserts
  337. // provided that no element with the given key already exists.
  338. //
  339. // The element may be constructed even if there already is an element with the
  340. // key in the container, in which case the newly constructed element will be
  341. // destroyed immediately. Prefer `try_emplace()` unless your key is not
  342. // copyable or moveable.
  343. //
  344. // If rehashing occurs due to the insertion, all iterators are invalidated.
  345. using Base::emplace_hint;
  346. // flat_hash_map::try_emplace()
  347. //
  348. // Inserts an element of the specified value by constructing it in-place
  349. // within the `flat_hash_map`, provided that no element with the given key
  350. // already exists. Unlike `emplace()`, if an element with the given key
  351. // already exists, we guarantee that no element is constructed.
  352. //
  353. // If rehashing occurs due to the insertion, all iterators are invalidated.
  354. // Overloads are listed below.
  355. //
  356. // pair<iterator, bool> try_emplace(const key_type& k, Args&&... args):
  357. // pair<iterator, bool> try_emplace(key_type&& k, Args&&... args):
  358. //
  359. // Inserts (via copy or move) the element of the specified key into the
  360. // `flat_hash_map`.
  361. //
  362. // iterator try_emplace(const_iterator hint,
  363. // const key_type& k, Args&&... args):
  364. // iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args):
  365. //
  366. // Inserts (via copy or move) the element of the specified key into the
  367. // `flat_hash_map` using the position of `hint` as a non-binding suggestion
  368. // for where to begin the insertion search.
  369. //
  370. // All `try_emplace()` overloads make the same guarantees regarding rvalue
  371. // arguments as `std::unordered_map::try_emplace()`, namely that these
  372. // functions will not move from rvalue arguments if insertions do not happen.
  373. using Base::try_emplace;
  374. // flat_hash_map::extract()
  375. //
  376. // Extracts the indicated element, erasing it in the process, and returns it
  377. // as a C++17-compatible node handle. Overloads are listed below.
  378. //
  379. // node_type extract(const_iterator position):
  380. //
  381. // Extracts the key,value pair of the element at the indicated position and
  382. // returns a node handle owning that extracted data.
  383. //
  384. // node_type extract(const key_type& x):
  385. //
  386. // Extracts the key,value pair of the element with a key matching the passed
  387. // key value and returns a node handle owning that extracted data. If the
  388. // `flat_hash_map` does not contain an element with a matching key, this
  389. // function returns an empty node handle.
  390. //
  391. // NOTE: when compiled in an earlier version of C++ than C++17,
  392. // `node_type::key()` returns a const reference to the key instead of a
  393. // mutable reference. We cannot safely return a mutable reference without
  394. // std::launder (which is not available before C++17).
  395. using Base::extract;
  396. // flat_hash_map::merge()
  397. //
  398. // Extracts elements from a given `source` flat hash map into this
  399. // `flat_hash_map`. If the destination `flat_hash_map` already contains an
  400. // element with an equivalent key, that element is not extracted.
  401. using Base::merge;
  402. // flat_hash_map::swap(flat_hash_map& other)
  403. //
  404. // Exchanges the contents of this `flat_hash_map` with those of the `other`
  405. // flat hash map.
  406. //
  407. // All iterators and references on the `flat_hash_map` remain valid, excepting
  408. // for the past-the-end iterator, which is invalidated.
  409. //
  410. // `swap()` requires that the flat hash map's hashing and key equivalence
  411. // functions be Swappable, and are exchanged using unqualified calls to
  412. // non-member `swap()`. If the map's allocator has
  413. // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
  414. // set to `true`, the allocators are also exchanged using an unqualified call
  415. // to non-member `swap()`; otherwise, the allocators are not swapped.
  416. using Base::swap;
  417. // flat_hash_map::rehash(count)
  418. //
  419. // Rehashes the `flat_hash_map`, setting the number of slots to be at least
  420. // the passed value. If the new number of slots increases the load factor more
  421. // than the current maximum load factor
  422. // (`count` < `size()` / `max_load_factor()`), then the new number of slots
  423. // will be at least `size()` / `max_load_factor()`.
  424. //
  425. // To force a rehash, pass rehash(0).
  426. //
  427. // NOTE: unlike behavior in `std::unordered_map`, references are also
  428. // invalidated upon a `rehash()`.
  429. using Base::rehash;
  430. // flat_hash_map::reserve(count)
  431. //
  432. // Sets the number of slots in the `flat_hash_map` to the number needed to
  433. // accommodate at least `count` total elements without exceeding the current
  434. // maximum load factor, and may rehash the container if needed.
  435. using Base::reserve;
  436. // flat_hash_map::at()
  437. //
  438. // Returns a reference to the mapped value of the element with key equivalent
  439. // to the passed key.
  440. using Base::at;
  441. // flat_hash_map::contains()
  442. //
  443. // Determines whether an element with a key comparing equal to the given `key`
  444. // exists within the `flat_hash_map`, returning `true` if so or `false`
  445. // otherwise.
  446. using Base::contains;
  447. // flat_hash_map::count(const Key& key) const
  448. //
  449. // Returns the number of elements with a key comparing equal to the given
  450. // `key` within the `flat_hash_map`. note that this function will return
  451. // either `1` or `0` since duplicate keys are not allowed within a
  452. // `flat_hash_map`.
  453. using Base::count;
  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. // flat_hash_map::find()
  461. //
  462. // Finds an element with the passed `key` within the `flat_hash_map`.
  463. using Base::find;
  464. // flat_hash_map::operator[]()
  465. //
  466. // Returns a reference to the value mapped to the passed key within the
  467. // `flat_hash_map`, performing an `insert()` if the key does not already
  468. // exist.
  469. //
  470. // If an insertion occurs and results in a rehashing of the container, all
  471. // iterators are invalidated. Otherwise iterators are not affected and
  472. // references are not invalidated. Overloads are listed below.
  473. //
  474. // T& operator[](const Key& key):
  475. //
  476. // Inserts an init_type object constructed in-place if the element with the
  477. // given key does not exist.
  478. //
  479. // T& operator[](Key&& key):
  480. //
  481. // Inserts an init_type object constructed in-place provided that an element
  482. // with the given key does not exist.
  483. using Base::operator[];
  484. // flat_hash_map::bucket_count()
  485. //
  486. // Returns the number of "buckets" within the `flat_hash_map`. Note that
  487. // because a flat hash map contains all elements within its internal storage,
  488. // this value simply equals the current capacity of the `flat_hash_map`.
  489. using Base::bucket_count;
  490. // flat_hash_map::load_factor()
  491. //
  492. // Returns the current load factor of the `flat_hash_map` (the average number
  493. // of slots occupied with a value within the hash map).
  494. using Base::load_factor;
  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. // flat_hash_map::get_allocator()
  513. //
  514. // Returns the allocator function associated with this `flat_hash_map`.
  515. using Base::get_allocator;
  516. // flat_hash_map::hash_function()
  517. //
  518. // Returns the hashing function used to hash the keys within this
  519. // `flat_hash_map`.
  520. using Base::hash_function;
  521. // flat_hash_map::key_eq()
  522. //
  523. // Returns the function used for comparing keys equality.
  524. using Base::key_eq;
  525. };
  526. // erase_if(flat_hash_map<>, Pred)
  527. //
  528. // Erases all elements that satisfy the predicate `pred` from the container `c`.
  529. // Returns the number of erased elements.
  530. template <typename K, typename V, typename H, typename E, typename A,
  531. typename Predicate>
  532. typename flat_hash_map<K, V, H, E, A>::size_type erase_if(
  533. flat_hash_map<K, V, H, E, A>& c, Predicate pred) {
  534. return container_internal::EraseIf(pred, &c);
  535. }
  536. // swap(flat_hash_map<>, flat_hash_map<>)
  537. //
  538. // Swaps the contents of two `flat_hash_map` containers.
  539. //
  540. // NOTE: we need to define this function template in order for
  541. // `flat_hash_set::swap` to be called instead of `std::swap`. Even though we
  542. // have `swap(raw_hash_set&, raw_hash_set&)` defined, that function requires a
  543. // derived-to-base conversion, whereas `std::swap` is a function template so
  544. // `std::swap` will be preferred by compiler.
  545. template <typename K, typename V, typename H, typename E, typename A>
  546. void swap(flat_hash_map<K, V, H, E, A>& x,
  547. flat_hash_map<K, V, H, E, A>& y) noexcept(noexcept(x.swap(y))) {
  548. x.swap(y);
  549. }
  550. namespace container_internal {
  551. // c_for_each_fast(flat_hash_map<>, Function)
  552. //
  553. // Container-based version of the <algorithm> `std::for_each()` function to
  554. // apply a function to a container's elements.
  555. // There is no guarantees on the order of the function calls.
  556. // Erasure and/or insertion of elements in the function is not allowed.
  557. template <typename K, typename V, typename H, typename E, typename A,
  558. typename Function>
  559. decay_t<Function> c_for_each_fast(const flat_hash_map<K, V, H, E, A>& c,
  560. Function&& f) {
  561. container_internal::ForEach(f, &c);
  562. return f;
  563. }
  564. template <typename K, typename V, typename H, typename E, typename A,
  565. typename Function>
  566. decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>& c,
  567. Function&& f) {
  568. container_internal::ForEach(f, &c);
  569. return f;
  570. }
  571. template <typename K, typename V, typename H, typename E, typename A,
  572. typename Function>
  573. decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>&& c,
  574. Function&& f) {
  575. container_internal::ForEach(f, &c);
  576. return f;
  577. }
  578. } // namespace container_internal
  579. namespace container_internal {
  580. template <class K, class V>
  581. struct FlatHashMapPolicy {
  582. using slot_policy = container_internal::map_slot_policy<K, V>;
  583. using slot_type = typename slot_policy::slot_type;
  584. using key_type = K;
  585. using mapped_type = V;
  586. using init_type = std::pair</*non const*/ key_type, mapped_type>;
  587. template <class Allocator, class... Args>
  588. static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
  589. slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
  590. }
  591. // Returns std::true_type in case destroy is trivial.
  592. template <class Allocator>
  593. static auto destroy(Allocator* alloc, slot_type* slot) {
  594. return slot_policy::destroy(alloc, slot);
  595. }
  596. template <class Allocator>
  597. static auto transfer(Allocator* alloc, slot_type* new_slot,
  598. slot_type* old_slot) {
  599. return slot_policy::transfer(alloc, new_slot, old_slot);
  600. }
  601. template <class F, class... Args>
  602. static decltype(absl::container_internal::DecomposePair(
  603. std::declval<F>(), std::declval<Args>()...))
  604. apply(F&& f, Args&&... args) {
  605. return absl::container_internal::DecomposePair(std::forward<F>(f),
  606. std::forward<Args>(args)...);
  607. }
  608. template <class Hash>
  609. static constexpr HashSlotFn get_hash_slot_fn() {
  610. return memory_internal::IsLayoutCompatible<K, V>::value
  611. ? &TypeErasedApplyToSlotFn<Hash, K>
  612. : nullptr;
  613. }
  614. static size_t space_used(const slot_type*) { return 0; }
  615. static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
  616. static V& value(std::pair<const K, V>* kv) { return kv->second; }
  617. static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
  618. };
  619. } // namespace container_internal
  620. namespace container_algorithm_internal {
  621. // Specialization of trait in absl/algorithm/container.h
  622. template <class Key, class T, class Hash, class KeyEqual, class Allocator>
  623. struct IsUnorderedContainer<
  624. absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
  625. } // namespace container_algorithm_internal
  626. ABSL_NAMESPACE_END
  627. } // namespace absl
  628. #endif // ABSL_CONTAINER_FLAT_HASH_MAP_H_