flat_hash_map.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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 `y_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 Y_ABSL_CONTAINER_FLAT_HASH_MAP_H_
  32. #define Y_ABSL_CONTAINER_FLAT_HASH_MAP_H_
  33. #include <cstddef>
  34. #include <memory>
  35. #include <type_traits>
  36. #include <utility>
  37. #include "y_absl/algorithm/container.h"
  38. #include "y_absl/base/attributes.h"
  39. #include "y_absl/base/macros.h"
  40. #include "y_absl/container/hash_container_defaults.h"
  41. #include "y_absl/container/internal/container_memory.h"
  42. #include "y_absl/container/internal/raw_hash_map.h" // IWYU pragma: export
  43. #include "y_absl/meta/type_traits.h"
  44. namespace y_absl {
  45. Y_ABSL_NAMESPACE_BEGIN
  46. namespace container_internal {
  47. template <class K, class V>
  48. struct FlatHashMapPolicy;
  49. } // namespace container_internal
  50. // -----------------------------------------------------------------------------
  51. // y_absl::flat_hash_map
  52. // -----------------------------------------------------------------------------
  53. //
  54. // An `y_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 `y_absl::Hash` hashing framework.
  71. // All fundamental and Abseil types that support the `y_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 `y_absl::Hash` framework, see
  74. // y_absl/hash/hash.h for information on extending Abseil hashing to user-defined
  75. // types.
  76. //
  77. // Using `y_absl::flat_hash_map` at interface boundaries in dynamically loaded
  78. // libraries (e.g. .dll, .so) is unsupported due to way `y_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 `y_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 `y_absl::node_hash_map`.
  101. //
  102. // Example:
  103. //
  104. // // Create a flat hash map of three strings (that map to strings)
  105. // y_absl::flat_hash_map<TString, TString> 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. // TString 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 Y_ABSL_INTERNAL_ATTRIBUTE_OWNER flat_hash_map
  124. : public y_absl::container_internal::raw_hash_map<
  125. y_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. // y_absl::flat_hash_map<int, TString> map1;
  138. //
  139. // * Initializer List constructor
  140. //
  141. // y_absl::flat_hash_map<int, TString> map2 =
  142. // {{1, "huey"}, {2, "dewey"}, {3, "louie"},};
  143. //
  144. // * Copy constructor
  145. //
  146. // y_absl::flat_hash_map<int, TString> map3(map2);
  147. //
  148. // * Copy assignment operator
  149. //
  150. // // Hash functor and Comparator are copied as well
  151. // y_absl::flat_hash_map<int, TString> map4;
  152. // map4 = map3;
  153. //
  154. // * Move constructor
  155. //
  156. // // Move is guaranteed efficient
  157. // y_absl::flat_hash_map<int, TString> map5(std::move(map4));
  158. //
  159. // * Move assignment operator
  160. //
  161. // // May be efficient if allocators are compatible
  162. // y_absl::flat_hash_map<int, TString> map6;
  163. // map6 = std::move(map5);
  164. //
  165. // * Range constructor
  166. //
  167. // std::vector<std::pair<int, TString>> v = {{1, "a"}, {2, "b"}};
  168. // y_absl::flat_hash_map<int, TString> 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 `y_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, avoiding invocation of any move, copy, or swap operations on
  406. // individual elements.
  407. //
  408. // All iterators and references on the `flat_hash_map` remain valid, excepting
  409. // for the past-the-end iterator, which is invalidated.
  410. //
  411. // `swap()` requires that the flat hash map's hashing and key equivalence
  412. // functions be Swappable, and are exchanged using unqualified calls to
  413. // non-member `swap()`. If the map's allocator has
  414. // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
  415. // set to `true`, the allocators are also exchanged using an unqualified call
  416. // to non-member `swap()`; otherwise, the allocators are not swapped.
  417. using Base::swap;
  418. // flat_hash_map::rehash(count)
  419. //
  420. // Rehashes the `flat_hash_map`, setting the number of slots to be at least
  421. // the passed value. If the new number of slots increases the load factor more
  422. // than the current maximum load factor
  423. // (`count` < `size()` / `max_load_factor()`), then the new number of slots
  424. // will be at least `size()` / `max_load_factor()`.
  425. //
  426. // To force a rehash, pass rehash(0).
  427. //
  428. // NOTE: unlike behavior in `std::unordered_map`, references are also
  429. // invalidated upon a `rehash()`.
  430. using Base::rehash;
  431. // flat_hash_map::reserve(count)
  432. //
  433. // Sets the number of slots in the `flat_hash_map` to the number needed to
  434. // accommodate at least `count` total elements without exceeding the current
  435. // maximum load factor, and may rehash the container if needed.
  436. using Base::reserve;
  437. // flat_hash_map::at()
  438. //
  439. // Returns a reference to the mapped value of the element with key equivalent
  440. // to the passed key.
  441. using Base::at;
  442. // flat_hash_map::contains()
  443. //
  444. // Determines whether an element with a key comparing equal to the given `key`
  445. // exists within the `flat_hash_map`, returning `true` if so or `false`
  446. // otherwise.
  447. using Base::contains;
  448. // flat_hash_map::count(const Key& key) const
  449. //
  450. // Returns the number of elements with a key comparing equal to the given
  451. // `key` within the `flat_hash_map`. note that this function will return
  452. // either `1` or `0` since duplicate keys are not allowed within a
  453. // `flat_hash_map`.
  454. using Base::count;
  455. // flat_hash_map::equal_range()
  456. //
  457. // Returns a closed range [first, last], defined by a `std::pair` of two
  458. // iterators, containing all elements with the passed key in the
  459. // `flat_hash_map`.
  460. using Base::equal_range;
  461. // flat_hash_map::find()
  462. //
  463. // Finds an element with the passed `key` within the `flat_hash_map`.
  464. using Base::find;
  465. // flat_hash_map::operator[]()
  466. //
  467. // Returns a reference to the value mapped to the passed key within the
  468. // `flat_hash_map`, performing an `insert()` if the key does not already
  469. // exist.
  470. //
  471. // If an insertion occurs and results in a rehashing of the container, all
  472. // iterators are invalidated. Otherwise iterators are not affected and
  473. // references are not invalidated. Overloads are listed below.
  474. //
  475. // T& operator[](const Key& key):
  476. //
  477. // Inserts an init_type object constructed in-place if the element with the
  478. // given key does not exist.
  479. //
  480. // T& operator[](Key&& key):
  481. //
  482. // Inserts an init_type object constructed in-place provided that an element
  483. // with the given key does not exist.
  484. using Base::operator[];
  485. // flat_hash_map::bucket_count()
  486. //
  487. // Returns the number of "buckets" within the `flat_hash_map`. Note that
  488. // because a flat hash map contains all elements within its internal storage,
  489. // this value simply equals the current capacity of the `flat_hash_map`.
  490. using Base::bucket_count;
  491. // flat_hash_map::load_factor()
  492. //
  493. // Returns the current load factor of the `flat_hash_map` (the average number
  494. // of slots occupied with a value within the hash map).
  495. using Base::load_factor;
  496. // flat_hash_map::max_load_factor()
  497. //
  498. // Manages the maximum load factor of the `flat_hash_map`. Overloads are
  499. // listed below.
  500. //
  501. // float flat_hash_map::max_load_factor()
  502. //
  503. // Returns the current maximum load factor of the `flat_hash_map`.
  504. //
  505. // void flat_hash_map::max_load_factor(float ml)
  506. //
  507. // Sets the maximum load factor of the `flat_hash_map` to the passed value.
  508. //
  509. // NOTE: This overload is provided only for API compatibility with the STL;
  510. // `flat_hash_map` will ignore any set load factor and manage its rehashing
  511. // internally as an implementation detail.
  512. using Base::max_load_factor;
  513. // flat_hash_map::get_allocator()
  514. //
  515. // Returns the allocator function associated with this `flat_hash_map`.
  516. using Base::get_allocator;
  517. // flat_hash_map::hash_function()
  518. //
  519. // Returns the hashing function used to hash the keys within this
  520. // `flat_hash_map`.
  521. using Base::hash_function;
  522. // flat_hash_map::key_eq()
  523. //
  524. // Returns the function used for comparing keys equality.
  525. using Base::key_eq;
  526. };
  527. // erase_if(flat_hash_map<>, Pred)
  528. //
  529. // Erases all elements that satisfy the predicate `pred` from the container `c`.
  530. // Returns the number of erased elements.
  531. template <typename K, typename V, typename H, typename E, typename A,
  532. typename Predicate>
  533. typename flat_hash_map<K, V, H, E, A>::size_type erase_if(
  534. flat_hash_map<K, V, H, E, A>& c, Predicate pred) {
  535. return container_internal::EraseIf(pred, &c);
  536. }
  537. namespace container_internal {
  538. // c_for_each_fast(flat_hash_map<>, Function)
  539. //
  540. // Container-based version of the <algorithm> `std::for_each()` function to
  541. // apply a function to a container's elements.
  542. // There is no guarantees on the order of the function calls.
  543. // Erasure and/or insertion of elements in the function is not allowed.
  544. template <typename K, typename V, typename H, typename E, typename A,
  545. typename Function>
  546. decay_t<Function> c_for_each_fast(const flat_hash_map<K, V, H, E, A>& c,
  547. Function&& f) {
  548. container_internal::ForEach(f, &c);
  549. return f;
  550. }
  551. template <typename K, typename V, typename H, typename E, typename A,
  552. typename Function>
  553. decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>& c,
  554. Function&& f) {
  555. container_internal::ForEach(f, &c);
  556. return f;
  557. }
  558. template <typename K, typename V, typename H, typename E, typename A,
  559. typename Function>
  560. decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>&& c,
  561. Function&& f) {
  562. container_internal::ForEach(f, &c);
  563. return f;
  564. }
  565. } // namespace container_internal
  566. namespace container_internal {
  567. template <class K, class V>
  568. struct FlatHashMapPolicy {
  569. using slot_policy = container_internal::map_slot_policy<K, V>;
  570. using slot_type = typename slot_policy::slot_type;
  571. using key_type = K;
  572. using mapped_type = V;
  573. using init_type = std::pair</*non const*/ key_type, mapped_type>;
  574. template <class Allocator, class... Args>
  575. static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
  576. slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
  577. }
  578. // Returns std::true_type in case destroy is trivial.
  579. template <class Allocator>
  580. static auto destroy(Allocator* alloc, slot_type* slot) {
  581. return slot_policy::destroy(alloc, slot);
  582. }
  583. template <class Allocator>
  584. static auto transfer(Allocator* alloc, slot_type* new_slot,
  585. slot_type* old_slot) {
  586. return slot_policy::transfer(alloc, new_slot, old_slot);
  587. }
  588. template <class F, class... Args>
  589. static decltype(y_absl::container_internal::DecomposePair(
  590. std::declval<F>(), std::declval<Args>()...))
  591. apply(F&& f, Args&&... args) {
  592. return y_absl::container_internal::DecomposePair(std::forward<F>(f),
  593. std::forward<Args>(args)...);
  594. }
  595. template <class Hash>
  596. static constexpr HashSlotFn get_hash_slot_fn() {
  597. return memory_internal::IsLayoutCompatible<K, V>::value
  598. ? &TypeErasedApplyToSlotFn<Hash, K>
  599. : nullptr;
  600. }
  601. static size_t space_used(const slot_type*) { return 0; }
  602. static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
  603. static V& value(std::pair<const K, V>* kv) { return kv->second; }
  604. static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
  605. };
  606. } // namespace container_internal
  607. namespace container_algorithm_internal {
  608. // Specialization of trait in y_absl/algorithm/container.h
  609. template <class Key, class T, class Hash, class KeyEqual, class Allocator>
  610. struct IsUnorderedContainer<
  611. y_absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {};
  612. } // namespace container_algorithm_internal
  613. Y_ABSL_NAMESPACE_END
  614. } // namespace y_absl
  615. #endif // Y_ABSL_CONTAINER_FLAT_HASH_MAP_H_