OpenTTD Source: src/core/flatset_type.hpp Source File

OpenTTD Source 15.3

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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#ifndef FLATSET_TYPE_HPP
11#define FLATSET_TYPE_HPP
12
19template <class Tkey, class Tcompare = std::less<>>
20 class 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) const
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 */
FlatSet
Flat set implementation that uses a sorted vector for storage.
Definition flatset_type.hpp:20
FlatSet::contains
bool contains(const Tkey &key) const
Test if a key exists in the set.
Definition flatset_type.hpp:57
FlatSet::erase
size_t erase(const Tkey &key)
Erase a key from the set.
Definition flatset_type.hpp:43
FlatSet::data
std::vector< Tkey > data
Sorted vector. of values.
Definition flatset_type.hpp:21
FlatSet::insert
std::pair< const_iterator, bool > insert(const Tkey &key)
Insert a key into the set, if it does not already exist.
Definition flatset_type.hpp:31