Skip to content

Commit 424313e

Browse files
committed
flat_map::append_sorted_unique
1 parent 141cd20 commit 424313e

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

container/flat_map.hpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,17 @@ class flat_map
384384
merge_sorted(std::move(incoming_keys), std::move(incoming_values));
385385
}
386386

387+
template <typename KeyArgument, typename MappedArgument>
388+
[[nodiscard]] bool append_sorted_unique(KeyArgument&& key, MappedArgument&& value)
389+
{
390+
assert_not_batching();
391+
if (!empty() && !_compare(_keys.back(), key))
392+
return false;
393+
_keys.emplace_back(std::forward<KeyArgument>(key));
394+
_values.emplace_back(std::forward<MappedArgument>(value));
395+
return true;
396+
}
397+
387398
void begin_batch()
388399
{
389400
assert_not_batching();

tests/test-app/flat_map_tests.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,24 @@ TEST_CASE("flat_map merges sorted bulk insertion", "[flat-map]")
156156
CHECK(std::equal(map.begin(), map.end(), expected.begin(), expected.end()));
157157
}
158158

159+
TEST_CASE("flat_map appends strictly ordered unique values without consuming rejected values", "[flat-map]")
160+
{
161+
flat_map<int, move_only_value> map;
162+
map.reserve(3);
163+
CHECK(map.append_sorted_unique(1, move_only_value(10)));
164+
CHECK(map.append_sorted_unique(3, move_only_value(30)));
165+
166+
move_only_value duplicate(300);
167+
CHECK_FALSE(map.append_sorted_unique(3, std::move(duplicate)));
168+
CHECK(duplicate.value == 300);
169+
move_only_value rejected(20);
170+
CHECK_FALSE(map.append_sorted_unique(2, std::move(rejected)));
171+
CHECK(rejected.value == 20);
172+
CHECK(map.size() == 2);
173+
CHECK(map.at(1).value == 10);
174+
CHECK(map.at(3).value == 30);
175+
}
176+
159177
TEST_CASE("flat_map bulk operations handle empty and non-overlapping ranges", "[flat-map]")
160178
{
161179
flat_map<int, int> map;

0 commit comments

Comments
 (0)