You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

flat_hash_set.h 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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_set.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // An `absl::flat_hash_set<T>` is an unordered associative container designed to
  20. // be a more efficient replacement for `std::unordered_set`. Like
  21. // `unordered_set`, search, insertion, and deletion of set elements can be done
  22. // as an `O(1)` operation. However, `flat_hash_set` (and other unordered
  23. // associative containers known as the collection of Abseil "Swiss tables")
  24. // contain other optimizations that result in both memory and computation
  25. // advantages.
  26. //
  27. // In most cases, your default choice for a hash set should be a set of type
  28. // `flat_hash_set`.
  29. #ifndef ABSL_CONTAINER_FLAT_HASH_SET_H_
  30. #define ABSL_CONTAINER_FLAT_HASH_SET_H_
  31. #include <type_traits>
  32. #include <utility>
  33. #include "absl/algorithm/container.h"
  34. #include "absl/base/macros.h"
  35. #include "absl/container/internal/container_memory.h"
  36. #include "absl/container/internal/hash_function_defaults.h" // IWYU pragma: export
  37. #include "absl/container/internal/raw_hash_set.h" // IWYU pragma: export
  38. #include "absl/memory/memory.h"
  39. namespace absl
  40. {
  41. ABSL_NAMESPACE_BEGIN
  42. namespace container_internal
  43. {
  44. template<typename T>
  45. struct FlatHashSetPolicy;
  46. } // namespace container_internal
  47. // -----------------------------------------------------------------------------
  48. // absl::flat_hash_set
  49. // -----------------------------------------------------------------------------
  50. //
  51. // An `absl::flat_hash_set<T>` is an unordered associative container which has
  52. // been optimized for both speed and memory footprint in most common use cases.
  53. // Its interface is similar to that of `std::unordered_set<T>` with the
  54. // following notable differences:
  55. //
  56. // * Requires keys that are CopyConstructible
  57. // * Supports heterogeneous lookup, through `find()` and `insert()`, provided
  58. // that the set is provided a compatible heterogeneous hashing function and
  59. // equality operator.
  60. // * Invalidates any references and pointers to elements within the table after
  61. // `rehash()`.
  62. // * Contains a `capacity()` member function indicating the number of element
  63. // slots (open, deleted, and empty) within the hash set.
  64. // * Returns `void` from the `erase(iterator)` overload.
  65. //
  66. // By default, `flat_hash_set` uses the `absl::Hash` hashing framework. All
  67. // fundamental and Abseil types that support the `absl::Hash` framework have a
  68. // compatible equality operator for comparing insertions into `flat_hash_set`.
  69. // If your type is not yet supported by the `absl::Hash` framework, see
  70. // absl/hash/hash.h for information on extending Abseil hashing to user-defined
  71. // types.
  72. //
  73. // Using `absl::flat_hash_set` at interface boundaries in dynamically loaded
  74. // libraries (e.g. .dll, .so) is unsupported due to way `absl::Hash` values may
  75. // be randomized across dynamically loaded libraries.
  76. //
  77. // NOTE: A `flat_hash_set` stores its keys directly inside its implementation
  78. // array to avoid memory indirection. Because a `flat_hash_set` is designed to
  79. // move data when rehashed, set keys will not retain pointer stability. If you
  80. // require pointer stability, consider using
  81. // `absl::flat_hash_set<std::unique_ptr<T>>`. If your type is not moveable and
  82. // you require pointer stability, consider `absl::node_hash_set` instead.
  83. //
  84. // Example:
  85. //
  86. // // Create a flat hash set of three strings
  87. // absl::flat_hash_set<std::string> ducks =
  88. // {"huey", "dewey", "louie"};
  89. //
  90. // // Insert a new element into the flat hash set
  91. // ducks.insert("donald");
  92. //
  93. // // Force a rehash of the flat hash set
  94. // ducks.rehash(0);
  95. //
  96. // // See if "dewey" is present
  97. // if (ducks.contains("dewey")) {
  98. // std::cout << "We found dewey!" << std::endl;
  99. // }
  100. template<class T, class Hash = absl::container_internal::hash_default_hash<T>, class Eq = absl::container_internal::hash_default_eq<T>, class Allocator = std::allocator<T>>
  101. class flat_hash_set : public absl::container_internal::raw_hash_set<absl::container_internal::FlatHashSetPolicy<T>, Hash, Eq, Allocator>
  102. {
  103. using Base = typename flat_hash_set::raw_hash_set;
  104. public:
  105. // Constructors and Assignment Operators
  106. //
  107. // A flat_hash_set supports the same overload set as `std::unordered_set`
  108. // for construction and assignment:
  109. //
  110. // * Default constructor
  111. //
  112. // // No allocation for the table's elements is made.
  113. // absl::flat_hash_set<std::string> set1;
  114. //
  115. // * Initializer List constructor
  116. //
  117. // absl::flat_hash_set<std::string> set2 =
  118. // {{"huey"}, {"dewey"}, {"louie"},};
  119. //
  120. // * Copy constructor
  121. //
  122. // absl::flat_hash_set<std::string> set3(set2);
  123. //
  124. // * Copy assignment operator
  125. //
  126. // // Hash functor and Comparator are copied as well
  127. // absl::flat_hash_set<std::string> set4;
  128. // set4 = set3;
  129. //
  130. // * Move constructor
  131. //
  132. // // Move is guaranteed efficient
  133. // absl::flat_hash_set<std::string> set5(std::move(set4));
  134. //
  135. // * Move assignment operator
  136. //
  137. // // May be efficient if allocators are compatible
  138. // absl::flat_hash_set<std::string> set6;
  139. // set6 = std::move(set5);
  140. //
  141. // * Range constructor
  142. //
  143. // std::vector<std::string> v = {"a", "b"};
  144. // absl::flat_hash_set<std::string> set7(v.begin(), v.end());
  145. flat_hash_set()
  146. {
  147. }
  148. using Base::Base;
  149. // flat_hash_set::begin()
  150. //
  151. // Returns an iterator to the beginning of the `flat_hash_set`.
  152. using Base::begin;
  153. // flat_hash_set::cbegin()
  154. //
  155. // Returns a const iterator to the beginning of the `flat_hash_set`.
  156. using Base::cbegin;
  157. // flat_hash_set::cend()
  158. //
  159. // Returns a const iterator to the end of the `flat_hash_set`.
  160. using Base::cend;
  161. // flat_hash_set::end()
  162. //
  163. // Returns an iterator to the end of the `flat_hash_set`.
  164. using Base::end;
  165. // flat_hash_set::capacity()
  166. //
  167. // Returns the number of element slots (assigned, deleted, and empty)
  168. // available within the `flat_hash_set`.
  169. //
  170. // NOTE: this member function is particular to `absl::flat_hash_set` and is
  171. // not provided in the `std::unordered_set` API.
  172. using Base::capacity;
  173. // flat_hash_set::empty()
  174. //
  175. // Returns whether or not the `flat_hash_set` is empty.
  176. using Base::empty;
  177. // flat_hash_set::max_size()
  178. //
  179. // Returns the largest theoretical possible number of elements within a
  180. // `flat_hash_set` under current memory constraints. This value can be thought
  181. // of the largest value of `std::distance(begin(), end())` for a
  182. // `flat_hash_set<T>`.
  183. using Base::max_size;
  184. // flat_hash_set::size()
  185. //
  186. // Returns the number of elements currently within the `flat_hash_set`.
  187. using Base::size;
  188. // flat_hash_set::clear()
  189. //
  190. // Removes all elements from the `flat_hash_set`. Invalidates any references,
  191. // pointers, or iterators referring to contained elements.
  192. //
  193. // NOTE: this operation may shrink the underlying buffer. To avoid shrinking
  194. // the underlying buffer call `erase(begin(), end())`.
  195. using Base::clear;
  196. // flat_hash_set::erase()
  197. //
  198. // Erases elements within the `flat_hash_set`. Erasing does not trigger a
  199. // rehash. Overloads are listed below.
  200. //
  201. // void erase(const_iterator pos):
  202. //
  203. // Erases the element at `position` of the `flat_hash_set`, returning
  204. // `void`.
  205. //
  206. // NOTE: returning `void` in this case is different than that of STL
  207. // containers in general and `std::unordered_set` in particular (which
  208. // return an iterator to the element following the erased element). If that
  209. // iterator is needed, simply post increment the iterator:
  210. //
  211. // set.erase(it++);
  212. //
  213. // iterator erase(const_iterator first, const_iterator last):
  214. //
  215. // Erases the elements in the open interval [`first`, `last`), returning an
  216. // iterator pointing to `last`.
  217. //
  218. // size_type erase(const key_type& key):
  219. //
  220. // Erases the element with the matching key, if it exists, returning the
  221. // number of elements erased (0 or 1).
  222. using Base::erase;
  223. // flat_hash_set::insert()
  224. //
  225. // Inserts an element of the specified value into the `flat_hash_set`,
  226. // returning an iterator pointing to the newly inserted element, provided that
  227. // an element with the given key does not already exist. If rehashing occurs
  228. // due to the insertion, all iterators are invalidated. Overloads are listed
  229. // below.
  230. //
  231. // std::pair<iterator,bool> insert(const T& value):
  232. //
  233. // Inserts a value into the `flat_hash_set`. Returns a pair consisting of an
  234. // iterator to the inserted element (or to the element that prevented the
  235. // insertion) and a bool denoting whether the insertion took place.
  236. //
  237. // std::pair<iterator,bool> insert(T&& value):
  238. //
  239. // Inserts a moveable value into the `flat_hash_set`. Returns a pair
  240. // consisting of an iterator to the inserted element (or to the element that
  241. // prevented the insertion) and a bool denoting whether the insertion took
  242. // place.
  243. //
  244. // iterator insert(const_iterator hint, const T& value):
  245. // iterator insert(const_iterator hint, T&& value):
  246. //
  247. // Inserts a value, using the position of `hint` as a non-binding suggestion
  248. // for where to begin the insertion search. Returns an iterator to the
  249. // inserted element, or to the existing element that prevented the
  250. // insertion.
  251. //
  252. // void insert(InputIterator first, InputIterator last):
  253. //
  254. // Inserts a range of values [`first`, `last`).
  255. //
  256. // NOTE: Although the STL does not specify which element may be inserted if
  257. // multiple keys compare equivalently, for `flat_hash_set` we guarantee the
  258. // first match is inserted.
  259. //
  260. // void insert(std::initializer_list<T> ilist):
  261. //
  262. // Inserts the elements within the initializer list `ilist`.
  263. //
  264. // NOTE: Although the STL does not specify which element may be inserted if
  265. // multiple keys compare equivalently within the initializer list, for
  266. // `flat_hash_set` we guarantee the first match is inserted.
  267. using Base::insert;
  268. // flat_hash_set::emplace()
  269. //
  270. // Inserts an element of the specified value by constructing it in-place
  271. // within the `flat_hash_set`, provided that no element with the given key
  272. // already exists.
  273. //
  274. // The element may be constructed even if there already is an element with the
  275. // key in the container, in which case the newly constructed element will be
  276. // destroyed immediately.
  277. //
  278. // If rehashing occurs due to the insertion, all iterators are invalidated.
  279. using Base::emplace;
  280. // flat_hash_set::emplace_hint()
  281. //
  282. // Inserts an element of the specified value by constructing it in-place
  283. // within the `flat_hash_set`, using the position of `hint` as a non-binding
  284. // suggestion for where to begin the insertion search, and only inserts
  285. // provided that no element with the given key already exists.
  286. //
  287. // The element may be constructed even if there already is an element with the
  288. // key in the container, in which case the newly constructed element will be
  289. // destroyed immediately.
  290. //
  291. // If rehashing occurs due to the insertion, all iterators are invalidated.
  292. using Base::emplace_hint;
  293. // flat_hash_set::extract()
  294. //
  295. // Extracts the indicated element, erasing it in the process, and returns it
  296. // as a C++17-compatible node handle. Overloads are listed below.
  297. //
  298. // node_type extract(const_iterator position):
  299. //
  300. // Extracts the element at the indicated position and returns a node handle
  301. // owning that extracted data.
  302. //
  303. // node_type extract(const key_type& x):
  304. //
  305. // Extracts the element with the key matching the passed key value and
  306. // returns a node handle owning that extracted data. If the `flat_hash_set`
  307. // does not contain an element with a matching key, this function returns an
  308. // empty node handle.
  309. using Base::extract;
  310. // flat_hash_set::merge()
  311. //
  312. // Extracts elements from a given `source` flat hash set into this
  313. // `flat_hash_set`. If the destination `flat_hash_set` already contains an
  314. // element with an equivalent key, that element is not extracted.
  315. using Base::merge;
  316. // flat_hash_set::swap(flat_hash_set& other)
  317. //
  318. // Exchanges the contents of this `flat_hash_set` with those of the `other`
  319. // flat hash set, avoiding invocation of any move, copy, or swap operations on
  320. // individual elements.
  321. //
  322. // All iterators and references on the `flat_hash_set` remain valid, excepting
  323. // for the past-the-end iterator, which is invalidated.
  324. //
  325. // `swap()` requires that the flat hash set's hashing and key equivalence
  326. // functions be Swappable, and are exchaged using unqualified calls to
  327. // non-member `swap()`. If the set's allocator has
  328. // `std::allocator_traits<allocator_type>::propagate_on_container_swap::value`
  329. // set to `true`, the allocators are also exchanged using an unqualified call
  330. // to non-member `swap()`; otherwise, the allocators are not swapped.
  331. using Base::swap;
  332. // flat_hash_set::rehash(count)
  333. //
  334. // Rehashes the `flat_hash_set`, setting the number of slots to be at least
  335. // the passed value. If the new number of slots increases the load factor more
  336. // than the current maximum load factor
  337. // (`count` < `size()` / `max_load_factor()`), then the new number of slots
  338. // will be at least `size()` / `max_load_factor()`.
  339. //
  340. // To force a rehash, pass rehash(0).
  341. //
  342. // NOTE: unlike behavior in `std::unordered_set`, references are also
  343. // invalidated upon a `rehash()`.
  344. using Base::rehash;
  345. // flat_hash_set::reserve(count)
  346. //
  347. // Sets the number of slots in the `flat_hash_set` to the number needed to
  348. // accommodate at least `count` total elements without exceeding the current
  349. // maximum load factor, and may rehash the container if needed.
  350. using Base::reserve;
  351. // flat_hash_set::contains()
  352. //
  353. // Determines whether an element comparing equal to the given `key` exists
  354. // within the `flat_hash_set`, returning `true` if so or `false` otherwise.
  355. using Base::contains;
  356. // flat_hash_set::count(const Key& key) const
  357. //
  358. // Returns the number of elements comparing equal to the given `key` within
  359. // the `flat_hash_set`. note that this function will return either `1` or `0`
  360. // since duplicate elements are not allowed within a `flat_hash_set`.
  361. using Base::count;
  362. // flat_hash_set::equal_range()
  363. //
  364. // Returns a closed range [first, last], defined by a `std::pair` of two
  365. // iterators, containing all elements with the passed key in the
  366. // `flat_hash_set`.
  367. using Base::equal_range;
  368. // flat_hash_set::find()
  369. //
  370. // Finds an element with the passed `key` within the `flat_hash_set`.
  371. using Base::find;
  372. // flat_hash_set::bucket_count()
  373. //
  374. // Returns the number of "buckets" within the `flat_hash_set`. Note that
  375. // because a flat hash set contains all elements within its internal storage,
  376. // this value simply equals the current capacity of the `flat_hash_set`.
  377. using Base::bucket_count;
  378. // flat_hash_set::load_factor()
  379. //
  380. // Returns the current load factor of the `flat_hash_set` (the average number
  381. // of slots occupied with a value within the hash set).
  382. using Base::load_factor;
  383. // flat_hash_set::max_load_factor()
  384. //
  385. // Manages the maximum load factor of the `flat_hash_set`. Overloads are
  386. // listed below.
  387. //
  388. // float flat_hash_set::max_load_factor()
  389. //
  390. // Returns the current maximum load factor of the `flat_hash_set`.
  391. //
  392. // void flat_hash_set::max_load_factor(float ml)
  393. //
  394. // Sets the maximum load factor of the `flat_hash_set` to the passed value.
  395. //
  396. // NOTE: This overload is provided only for API compatibility with the STL;
  397. // `flat_hash_set` will ignore any set load factor and manage its rehashing
  398. // internally as an implementation detail.
  399. using Base::max_load_factor;
  400. // flat_hash_set::get_allocator()
  401. //
  402. // Returns the allocator function associated with this `flat_hash_set`.
  403. using Base::get_allocator;
  404. // flat_hash_set::hash_function()
  405. //
  406. // Returns the hashing function used to hash the keys within this
  407. // `flat_hash_set`.
  408. using Base::hash_function;
  409. // flat_hash_set::key_eq()
  410. //
  411. // Returns the function used for comparing keys equality.
  412. using Base::key_eq;
  413. };
  414. // erase_if(flat_hash_set<>, Pred)
  415. //
  416. // Erases all elements that satisfy the predicate `pred` from the container `c`.
  417. // Returns the number of erased elements.
  418. template<typename T, typename H, typename E, typename A, typename Predicate>
  419. typename flat_hash_set<T, H, E, A>::size_type erase_if(
  420. flat_hash_set<T, H, E, A>& c, Predicate pred
  421. )
  422. {
  423. return container_internal::EraseIf(pred, &c);
  424. }
  425. namespace container_internal
  426. {
  427. template<class T>
  428. struct FlatHashSetPolicy
  429. {
  430. using slot_type = T;
  431. using key_type = T;
  432. using init_type = T;
  433. using constant_iterators = std::true_type;
  434. template<class Allocator, class... Args>
  435. static void construct(Allocator* alloc, slot_type* slot, Args&&... args)
  436. {
  437. absl::allocator_traits<Allocator>::construct(*alloc, slot, std::forward<Args>(args)...);
  438. }
  439. template<class Allocator>
  440. static void destroy(Allocator* alloc, slot_type* slot)
  441. {
  442. absl::allocator_traits<Allocator>::destroy(*alloc, slot);
  443. }
  444. template<class Allocator>
  445. static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot)
  446. {
  447. construct(alloc, new_slot, std::move(*old_slot));
  448. destroy(alloc, old_slot);
  449. }
  450. static T& element(slot_type* slot)
  451. {
  452. return *slot;
  453. }
  454. template<class F, class... Args>
  455. static decltype(absl::container_internal::DecomposeValue(
  456. std::declval<F>(), std::declval<Args>()...
  457. ))
  458. apply(F&& f, Args&&... args)
  459. {
  460. return absl::container_internal::DecomposeValue(
  461. std::forward<F>(f), std::forward<Args>(args)...
  462. );
  463. }
  464. static size_t space_used(const T*)
  465. {
  466. return 0;
  467. }
  468. };
  469. } // namespace container_internal
  470. namespace container_algorithm_internal
  471. {
  472. // Specialization of trait in absl/algorithm/container.h
  473. template<class Key, class Hash, class KeyEqual, class Allocator>
  474. struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>> : std::true_type
  475. {
  476. };
  477. } // namespace container_algorithm_internal
  478. ABSL_NAMESPACE_END
  479. } // namespace absl
  480. #endif // ABSL_CONTAINER_FLAT_HASH_SET_H_