OpenTTD Source 20250705-master-gebd984d894
flatset_type.hpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10#ifndef FLATSET_TYPE_HPP
11#define FLATSET_TYPE_HPP
12
19template <class Tkey, class Tcompare = std::less<>>
20class FlatSet {
21 std::vector<Tkey> data;
22public:
23 using const_iterator = std::vector<Tkey>::const_iterator;
24
31 std::pair<const_iterator, bool> insert(const Tkey &key)
32 {
33 auto it = std::ranges::lower_bound(this->data, key, Tcompare{});
34 if (it == std::end(this->data) || *it != key) return {this->data.emplace(it, key), true};
35 return {it, false};
36 }
37
43 size_t erase(const Tkey &key)
44 {
45 auto it = std::ranges::lower_bound(this->data, key, Tcompare{});
46 if (it == std::end(this->data) || *it != key) return 0;
47
48 this->data.erase(it);
49 return 1;
50 }
51
57 bool contains(const Tkey &key)
58 {
59 return std::ranges::binary_search(this->data, key, Tcompare{});
60 }
61
62 const_iterator begin() const { return std::cbegin(this->data); }
63 const_iterator end() const { return std::cend(this->data); }
64
65 const_iterator cbegin() const { return std::cbegin(this->data); }
66 const_iterator cend() const { return std::cend(this->data); }
67
68 size_t size() const { return std::size(this->data); }
69 bool empty() const { return this->data.empty(); }
70
71 void clear() { this->data.clear(); }
72
73 auto operator<=>(const FlatSet<Tkey, Tcompare> &) const = default;
74};
75
76#endif /* FLATSET_TYPE_HPP */
Flat set implementation that uses a sorted vector for storage.
bool contains(const Tkey &key)
Test if a key exists in the set.
size_t erase(const Tkey &key)
Erase a key from the set.
std::vector< Tkey > data
Sorted vector. of values.
std::pair< const_iterator, bool > insert(const Tkey &key)
Insert a key into the set, if it does not already exist.