flat_hash_set.h 18 KB

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