Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_flat_set.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
66#ifndef TPL_FLAT_SET_H
67#define TPL_FLAT_SET_H
68
69#include <algorithm>
70#include <initializer_list>
71#include <iterator>
72#include <type_traits>
73#include <utility>
74
75#include <ah-errors.H>
76#include <ahFunction.H>
77#include <tpl_memArray.H>
78#include <tpl_sort_utils.H>
79
80namespace Aleph {
81
142template <typename Key, class Compare = Aleph::less<Key>>
144{
146 Compare cmp_;
147
148 // Index of the first element not less than k (lower bound position).
149 size_t lower_idx(const Key &k) const
150 {
151 size_t lo = 0, hi = keys_.size();
152 while (lo < hi)
153 if (const size_t mid = lo + ((hi - lo) >> 1); cmp_(keys_(mid), k))
154 lo = mid + 1;
155 else
156 hi = mid;
157 return lo;
158 }
159
160 // Index of the first element greater than k (upper bound position).
161 size_t upper_idx(const Key &k) const
162 {
163 size_t lo = 0, hi = keys_.size();
164 while (lo < hi)
165 if (const size_t mid = lo + ((hi - lo) >> 1); not cmp_(k, keys_(mid)))
166 lo = mid + 1;
167 else
168 hi = mid;
169 return lo;
170 }
171
172 // True if pos holds a key equivalent to k. Assumes pos == lower_idx(k),
173 // so only the second half of the equivalence needs testing.
174 bool match_at(size_t pos, const Key &k) const
175 {
176 return pos < keys_.size() and not cmp_(k, keys_(pos));
177 }
178
179 // True if keys can be moved without throwing. A shift or a relocation
180 // then always completes, and the only way an insertion can fail is an
181 // allocation that leaves the keys untouched.
182 static constexpr bool nothrow_relocation =
183 std::is_nothrow_move_constructible_v<Key> and
184 std::is_nothrow_move_assignable_v<Key>;
185
186 // Runs op, which moves keys inside the array. If such a move can throw,
187 // an exception may leave a key moved from or duplicated. The set is then
188 // emptied, which restores its invariants as std::flat_set does, and the
189 // exception continues.
190 template <class Op>
191 void keeping_invariants(Op &&op)
192 {
193 if constexpr (nothrow_relocation)
194 op();
195 else
196 try
197 {
198 op();
199 }
200 catch (...)
201 {
202 empty();
203 throw;
204 }
205 }
206
207 // Gives the array room for cap keys. If the keys cannot throw when
208 // moved, MemArray::reserve() either completes or fails before it moves
209 // any. Otherwise the new buffer is obtained here first, so that a cap out
210 // of range or an allocation that fails leaves the keys untouched; only a
211 // move that throws afterwards is left to keeping_invariants().
212 void grow_to(const size_t cap)
213 {
214 if (cap <= keys_.capacity())
215 return;
216
217 if constexpr (nothrow_relocation)
218 keys_.reserve(cap);
219 else
220 {
221 MemArray<Key> fresh(cap);
223 {
224 const size_t n = keys_.size();
225 fresh.putn(n);
226 Key *from = keys_.get_ptr();
227 Key *to = fresh.get_ptr();
228 for (size_t i = 0; i < n; ++i)
229 to[i] = std::move(from[i]);
230 keys_.swap(fresh);
231 });
232 }
233 }
234
235 // Opens one slot at pos by shifting [pos, n) one place right. The array
236 // has room for it: growing is a matter of grow_to().
237 void make_room(const size_t pos)
238 {
239 keys_.putn(1);
240 Key *p = keys_.get_ptr();
241 for (size_t i = keys_.size() - 1; i > pos; --i)
242 p[i] = std::move(p[i - 1]);
243 }
244
245 // Stores k in a new slot at pos. The key is built before the array
246 // changes, so a copy that throws leaves the set untouched.
247 template <class K>
248 void insert_at(const size_t pos, K &&k)
249 {
250 Key key(std::forward<K>(k));
251
252 // A full array doubles. One emptied by a move has no storage at all and
253 // starts again at the minimum, as MemArray does on its own.
254 if (const size_t n = keys_.size(); n == keys_.capacity())
255 grow_to(std::max(n + 1, MemArray<Key>::Min_Dim));
256
258 {
259 make_room(pos);
260 keys_.get_ptr()[pos] = std::move(key);
261 });
262 }
263
264 // Removes the slot at pos by shifting (pos, n) one place left.
265 void remove_at(const size_t pos)
266 {
268 {
269 Key *p = keys_.get_ptr();
270 const size_t last = keys_.size() - 1;
271 for (size_t i = pos; i < last; ++i)
272 p[i] = std::move(p[i + 1]);
273 if constexpr (nothrow_relocation)
274 try
275 {
276 (void) keys_.get();
277 }
278 catch (...)
279 {
280 // A shrinking reallocation can only fail before it moves a
281 // key; the logical removal already took effect because the
282 // element count was decremented first.
283 }
284 else
285 (void) keys_.get();
286 });
287 }
288
289 // Sorts the freshly loaded backing array and drops duplicates, keeping
290 // the first occurrence of each equivalence class.
292 {
293 Key *p = keys_.get_ptr();
294 timsort(p, keys_.size(), cmp_);
295 size_t m = 0;
296 for (size_t i = 0; i < keys_.size(); ++i)
297 if (m == 0 or cmp_(p[m - 1], p[i]))
298 {
299 if (i != m)
300 p[m] = std::move(p[i]);
301 ++m;
302 }
303 const size_t excess = keys_.size() - m;
304 if (excess > 0)
305 try
306 {
307 (void) keys_.get(excess);
308 }
309 catch (const std::bad_alloc &)
310 { /* shrink failed; logical removal already done */ }
311 }
312
313public:
314 using Item_Type = Key;
315 using Key_Type = Key;
316 using key_type = Key;
317 using value_type = Key;
318 using key_compare = Compare;
319 using size_type = size_t;
320 using iterator = const Key *;
321 using const_iterator = const Key *;
322
329 explicit FlatSet(size_t cap = MemArray<Key>::Min_Dim) : keys_(cap) {}
330
337 explicit FlatSet(const Compare &cmp, size_t cap = MemArray<Key>::Min_Dim) : keys_(cap), cmp_(cmp)
338 {}
339
352 template <std::input_iterator It>
353 FlatSet(It first, It last, const Compare &cmp = Compare())
354 : keys_(MemArray<Key>::Min_Dim), cmp_(cmp)
355 {
356 for (; first != last; ++first)
357 keys_.put(*first);
359 }
360
367 FlatSet(std::initializer_list<Key> l, const Compare &cmp = Compare())
368 : FlatSet(l.begin(), l.end(), cmp)
369 {}
370
372 FlatSet(const FlatSet &) = default;
373
375 FlatSet(FlatSet &&) noexcept = default;
376
378 FlatSet &operator = (const FlatSet &) = default;
379
381 FlatSet &operator = (FlatSet &&) noexcept = default;
382
383 ~FlatSet() = default;
384
388 void swap(FlatSet &s) noexcept(std::is_nothrow_swappable_v<Compare>)
389 {
390 keys_.swap(s.keys_);
391 std::swap(cmp_, s.cmp_);
392 }
393
394 // -- capacity -------------------------------------------------------------
395
397 [[nodiscard]] size_t size() const noexcept
398 {
399 return keys_.size();
400 }
401
403 [[nodiscard]] bool is_empty() const noexcept
404 {
405 return keys_.is_empty();
406 }
407
409 [[nodiscard]] size_t capacity() const noexcept
410 {
411 return keys_.capacity();
412 }
413
423 void reserve(size_t cap)
424 {
425 grow_to(cap);
426 }
427
432 void empty() noexcept
433 {
434 keys_.empty();
435 }
436
438 void clear() noexcept
439 {
440 keys_.clear();
441 }
442
443 // -- lookup ---------------------------------------------------------------
444
450 const_iterator find(const Key &k) const
451 {
452 const size_t pos = lower_idx(k);
453 return match_at(pos, k) ? begin() + pos : end();
454 }
455
461 [[nodiscard]] bool contains(const Key &k) const
462 {
463 return match_at(lower_idx(k), k);
464 }
465
471 [[nodiscard]] size_t count(const Key &k) const
472 {
473 return contains(k) ? 1 : 0;
474 }
475
481 const_iterator lower_bound(const Key &k) const
482 {
483 return begin() + lower_idx(k);
484 }
485
491 const_iterator upper_bound(const Key &k) const
492 {
493 return begin() + upper_idx(k);
494 }
495
501 std::pair<const_iterator, const_iterator> equal_range(const Key &k) const
502 {
503 return {lower_bound(k), upper_bound(k)};
504 }
505
512 const Key &nth(size_t i) const
513 {
514 return keys_[i];
515 }
516
521 const Key &operator () (size_t i) const noexcept
522 {
523 return keys_(i);
524 }
525
530 const Key &get_first() const
531 {
532 ah_underflow_error_if(is_empty()) << "FlatSet::get_first(): empty set";
533 return keys_(0);
534 }
535
540 const Key &get_last() const
541 {
542 ah_underflow_error_if(is_empty()) << "FlatSet::get_last(): empty set";
543 return keys_(keys_.size() - 1);
544 }
545
547 const Key &min() const
548 {
549 return get_first();
550 }
551
553 const Key &max() const
554 {
555 return get_last();
556 }
557
558 // -- modifiers ------------------------------------------------------------
559
567 std::pair<const_iterator, bool> insert(const Key &k)
568 {
569 const size_t pos = lower_idx(k);
570 if (match_at(pos, k))
571 return {begin() + pos, false};
572 insert_at(pos, k);
573 return {begin() + pos, true};
574 }
575
582 std::pair<const_iterator, bool> insert(Key &&k)
583 {
584 const size_t pos = lower_idx(k);
585 if (match_at(pos, k))
586 return {begin() + pos, false};
587 insert_at(pos, std::move(k));
588 return {begin() + pos, true};
589 }
590
602 template <class... Args>
603 std::pair<const_iterator, bool> emplace(Args &&...args)
604 {
605 return insert(Key(std::forward<Args>(args)...));
606 }
607
617 size_t erase(const Key &k)
618 {
619 const size_t pos = lower_idx(k);
620 if (not match_at(pos, k))
621 return 0;
622 remove_at(pos);
623 return 1;
624 }
625
633 {
634 const size_t pos = it - begin();
635 ah_out_of_range_error_if(pos >= size()) << "FlatSet::erase(): iterator out of range";
636 remove_at(pos);
637 return begin() + pos;
638 }
639
640 // -- iteration ------------------------------------------------------------
641
643 const_iterator begin() const noexcept
644 {
645 return keys_.get_ptr();
646 }
647
649 const_iterator end() const noexcept
650 {
651 return keys_.get_ptr() + keys_.size();
652 }
653
655 const_iterator cbegin() const noexcept
656 {
657 return begin();
658 }
659
661 const_iterator cend() const noexcept
662 {
663 return end();
664 }
665
667 const Key *data() const noexcept
668 {
669 return keys_.get_ptr();
670 }
671
681 template <class Operation>
682 bool traverse(Operation operation) const
683 {
684 const Key *p = keys_.get_ptr();
685 const size_t m = keys_.size();
686 for (size_t i = 0; i < m; ++i)
687 if (not operation(p[i]))
688 return false;
689 return true;
690 }
691
692 // -- comparison -----------------------------------------------------------
693
699 bool operator == (const FlatSet &s) const
700 {
701 return size() == s.size() and std::equal(begin(), end(), s.begin());
702 }
703
705 bool operator != (const FlatSet &s) const
706 {
707 return not (*this == s);
708 }
709};
710
711} // end namespace Aleph
712
713#endif // TPL_FLAT_SET_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
Definition ah-errors.H:517
Standard functor implementations and comparison objects.
Ordered set stored as a sorted contiguous array.
const Key * iterator
Random-access iterator (immutable).
const Key * const_iterator
Random-access const iterator.
const_iterator erase(const_iterator it)
Remove the key at iterator it.
FlatSet(const Compare &cmp, size_t cap=MemArray< Key >::Min_Dim)
Construct an empty set with a specific comparator.
void make_room(const size_t pos)
size_t capacity() const noexcept
Return the capacity of the backing array. O(1).
bool operator==(const FlatSet &s) const
Equality: same size and pairwise equal elements.
void sort_and_unique()
const Key & min() const
Smallest key (checked). Alias of get_first().
size_t upper_idx(const Key &k) const
const_iterator upper_bound(const Key &k) const
First element greater than k.
size_t erase(const Key &k)
Remove the key equivalent to k, if present.
FlatSet(std::initializer_list< Key > l, const Compare &cmp=Compare())
Construct from an initializer list.
FlatSet(It first, It last, const Compare &cmp=Compare())
Construct from an iterator range.
size_t lower_idx(const Key &k) const
void keeping_invariants(Op &&op)
Key value_type
STL convention: value type.
Key Item_Type
Aleph convention: element type.
const_iterator end() const noexcept
Iterator past the greatest key. O(1).
Key key_type
STL convention: key type.
const_iterator find(const Key &k) const
Find a key.
FlatSet(const FlatSet &)=default
Copy constructor (requires copyable Key).
FlatSet(size_t cap=MemArray< Key >::Min_Dim)
Construct an empty set.
bool match_at(size_t pos, const Key &k) const
std::pair< const_iterator, bool > insert(Key &&k)
Insert k by moving if no equivalent key exists.
void empty() noexcept
Remove all keys (Aleph convention).
Compare key_compare
STL convention: comparator type.
size_t count(const Key &k) const
Count occurrences of a key (0 or 1).
FlatSet(FlatSet &&) noexcept=default
Move constructor. The source is left valid but unspecified.
std::pair< const_iterator, bool > emplace(Args &&...args)
Construct a key in place and insert it.
std::pair< const_iterator, const_iterator > equal_range(const Key &k) const
Range of elements equivalent to k.
const_iterator cend() const noexcept
Const iterator past the greatest key. O(1).
void clear() noexcept
Remove all keys. Alias of empty(). Capacity is kept.
MemArray< Key > keys_
const Key & operator()(size_t i) const noexcept
Positional access without bounds checking.
const Key & max() const
Greatest key (checked). Alias of get_last().
bool traverse(Operation operation) const
Traverse keys in sorted order while operation returns true.
const Key * data() const noexcept
Pointer to the underlying sorted, contiguous storage. O(1).
void reserve(size_t cap)
Reserve capacity for at least cap keys.
const_iterator lower_bound(const Key &k) const
First element not less than k.
void grow_to(const size_t cap)
bool contains(const Key &k) const
Test membership.
size_t size() const noexcept
Return the number of stored keys. O(1).
size_t size_type
STL convention: size type.
bool is_empty() const noexcept
Return true if the set holds no keys. O(1).
const Key & get_first() const
Smallest key (checked).
const_iterator cbegin() const noexcept
Const iterator to the smallest key. O(1).
const Key & nth(size_t i) const
Positional access to the i-th smallest key (checked).
std::pair< const_iterator, bool > insert(const Key &k)
Insert a copy of k if no equivalent key exists.
void insert_at(const size_t pos, K &&k)
Key Key_Type
Aleph convention: key type.
void remove_at(const size_t pos)
const Key & get_last() const
Greatest key (checked).
static constexpr bool nothrow_relocation
void swap(FlatSet &s) noexcept(std::is_nothrow_swappable_v< Compare >)
Swap contents with s in O(1).
bool operator!=(const FlatSet &s) const
Inequality: negation of operator==.
const_iterator begin() const noexcept
Iterator to the smallest key. O(1).
Simple, scalable and fast dynamic array.
T & put(const T &item)
Put a copy of item at the end of the sequence.
void reserve(const size_t cap)
Reserves cap cells into the array.
size_t size() const noexcept
Return the number of elements.
void putn(const size_t more)
Reserve more additional logical slots in the array.
void clear() noexcept
Alias for empty().
T get(const size_t i=1)
Remove i elements from the end.
constexpr size_t capacity() const noexcept
The type of element of array.
bool is_empty() const noexcept
Return true is the array is empty.
void empty() noexcept
Empties the container.
T * get_ptr() noexcept
Return the current base of array.
void swap(MemArray &a) noexcept
Swap in constant time this with a
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
Main namespace for Aleph-w library functions.
void timsort(T *a, const size_t n, const Compare &cmp=Compare())
Timsort — adaptive, stable, natural merge sort.
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Simple, scalable, contiguous dynamic array.
Comprehensive sorting algorithms and search utilities for Aleph-w.
DynList< int > l