From 6f19d0a479992e3a96944631e92fb45379928edb Mon Sep 17 00:00:00 2001 From: Mathew Sutcliffe Date: Sat, 25 Jan 2014 19:26:57 +0000 Subject: [PATCH] containers: added methods contains(), remove(), replace(), replaceOrAdd(), corresponding to contains(), removeIf(), replaceIf(), and replaceOrAdd(), but overloaded for const T& as well as for predicates. refs #106 --- src/blackmisc/containerbase.h | 10 ++++++++++ src/blackmisc/sequence.h | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/blackmisc/containerbase.h b/src/blackmisc/containerbase.h index e9558aff0..ed9b7b1b8 100644 --- a/src/blackmisc/containerbase.h +++ b/src/blackmisc/containerbase.h @@ -94,6 +94,16 @@ namespace BlackMisc return std::any_of(derived().begin(), derived().end(), p); } + /*! + * \brief Return true if there is an element equal to given object + * \param object is this object in container? + * \return + */ + bool contains(const T &object) const + { + return std::find(derived().begin(), derived().end(), object) != derived().end(); + } + /*! * \brief Return a copy containing only those elements matching a particular key/value pair. * \param key1 A pointer to a member function of T. diff --git a/src/blackmisc/sequence.h b/src/blackmisc/sequence.h index cf76a70f1..ac8d30efe 100644 --- a/src/blackmisc/sequence.h +++ b/src/blackmisc/sequence.h @@ -267,6 +267,22 @@ namespace BlackMisc removeIf(BlackMisc::Predicates::MemberEqual(key1, value1)); } + /*! + * \brief Remove the given object, if it is contained. + */ + void remove(const T &object) + { + std::remove(begin(), end(), object); + } + + /*! + * \brief Replace elements matching the given element with a replacement. + */ + void replace(const T &original, const T &replacement) + { + std::replace(begin(), end(), original, replacement); + } + /*! * \brief Replace elements for which a given predicate returns true. */ @@ -297,6 +313,15 @@ namespace BlackMisc else { push_back(replacement); } } + /*! + * \brief Replace elements matching the given element. If there is no match, push the new element on the end. + */ + void replaceOrAdd(const T &original, const T &replacement) + { + if (this->contains(original)) { replace(original, replacement); } + else { push_back(replacement); } + } + /*! * \brief Replace elements matching a particular key/value pair. If there is no match, push the new element on the end. * \param key1 A pointer to a member function of T.