From f0de6395e84c665cd432dcda3c30a1d51b3eb485 Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Mon, 15 Apr 2019 16:32:02 +0100 Subject: [PATCH] Add convenience method sharing_mapt::erase_if_exists Just saves repeating the if-has-key-then-erase pattern --- src/util/sharing_map.h | 13 +++++++++++++ unit/util/sharing_map.cpp | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/src/util/sharing_map.h b/src/util/sharing_map.h index 0d9e307a6a..749776f0f8 100644 --- a/src/util/sharing_map.h +++ b/src/util/sharing_map.h @@ -222,6 +222,19 @@ public: /// \param k: The key of the element to erase void erase(const key_type &k); + /// Erase element if it exists + /// + /// Complexity: + /// - Worst case: O(H * S + M) + /// - Best case: O(H) + /// + /// \param k: The key of the element to erase + void erase_if_exists(const key_type &k) + { + if(has_key(k)) + erase(k); + } + /// Insert element, element must not exist in map /// /// Complexity: diff --git a/unit/util/sharing_map.cpp b/unit/util/sharing_map.cpp index b44a2e9b03..78b08cf222 100644 --- a/unit/util/sharing_map.cpp +++ b/unit/util/sharing_map.cpp @@ -201,6 +201,12 @@ TEST_CASE("Sharing map interface", "[core][util]") sm.erase("j"); REQUIRE(!sm.has_key("j")); + sm.erase_if_exists("j"); + REQUIRE(!sm.has_key("j")); + sm.insert("j", "1"); + sm.erase_if_exists("j"); + REQUIRE(!sm.has_key("j")); + sm.insert("i", "0"); sm.insert("j", "1");