mirror of https://github.com/OpenTTD/OpenTTD
Codechange: Give FlatSet insert() a return value.
This now returns an iterator, and whether an insert was performed. Allows the caller to know if the item was already in the FlatSet without explicitly checking first.pull/14389/head
parent
8f01ae675e
commit
d68207a572
|
@ -23,13 +23,16 @@ public:
|
|||
using const_iterator = std::vector<Tkey>::const_iterator;
|
||||
|
||||
/**
|
||||
* Insert a key into the set.
|
||||
* Insert a key into the set, if it does not already exist.
|
||||
* @param key Key to insert.
|
||||
* @return A pair consisting of an iterator to the inserted element (or to the element that prevented the
|
||||
* insertion), and a bool value to true iff the insertion took place.
|
||||
*/
|
||||
void insert(const Tkey &key)
|
||||
std::pair<const_iterator, bool> insert(const Tkey &key)
|
||||
{
|
||||
auto it = std::ranges::lower_bound(this->data, key, Tcompare{});
|
||||
if (it == std::end(this->data) || *it != key) this->data.emplace(it, key);
|
||||
if (it == std::end(this->data) || *it != key) return {this->data.emplace(it, key), true};
|
||||
return {it, false};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -28,11 +28,11 @@ TEST_CASE("FlatSet - basic")
|
|||
CHECK(set.empty());
|
||||
|
||||
/* Insert in a random order,. */
|
||||
set.insert(values[1]);
|
||||
set.insert(values[2]);
|
||||
set.insert(values[4]);
|
||||
set.insert(values[3]);
|
||||
set.insert(values[0]);
|
||||
CHECK(set.insert(values[1]).second);
|
||||
CHECK(set.insert(values[2]).second);
|
||||
CHECK(set.insert(values[4]).second);
|
||||
CHECK(set.insert(values[3]).second);
|
||||
CHECK(set.insert(values[0]).second);
|
||||
CHECK(set.size() == 5);
|
||||
CHECK(set.contains(values[0]));
|
||||
CHECK(set.contains(values[1]));
|
||||
|
@ -42,7 +42,7 @@ TEST_CASE("FlatSet - basic")
|
|||
CHECK(std::ranges::equal(set, values));
|
||||
|
||||
/* Test inserting an existing value does not affect order. */
|
||||
set.insert(values[1]);
|
||||
CHECK_FALSE(set.insert(values[1]).second);
|
||||
CHECK(set.size() == 5);
|
||||
CHECK(set.contains(values[0]));
|
||||
CHECK(set.contains(values[1]));
|
||||
|
@ -52,16 +52,16 @@ TEST_CASE("FlatSet - basic")
|
|||
CHECK(std::ranges::equal(set, values));
|
||||
|
||||
/* Insert a value multiple times. */
|
||||
set.insert(0);
|
||||
set.insert(0);
|
||||
set.insert(0);
|
||||
CHECK(set.insert(0).second);
|
||||
CHECK_FALSE(set.insert(0).second);
|
||||
CHECK_FALSE(set.insert(0).second);
|
||||
CHECK(set.size() == 6);
|
||||
CHECK(set.contains(0));
|
||||
|
||||
/* Remove a value multiple times. */
|
||||
set.erase(0);
|
||||
set.erase(0);
|
||||
set.erase(0);
|
||||
CHECK(set.erase(0) == 1);
|
||||
CHECK(set.erase(0) == 0);
|
||||
CHECK(set.erase(0) == 0);
|
||||
CHECK(set.size() == 5);
|
||||
CHECK(!set.contains(0));
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue