From d8091df47d88c63541be9be9ca1420f8dc1a24c5 Mon Sep 17 00:00:00 2001 From: Mathew Sutcliffe Date: Mon, 1 Jun 2015 18:08:06 +0100 Subject: [PATCH] refs #414 Efficient findFirstBy methods in CRangeBase. --- src/blackmisc/range.h | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/blackmisc/range.h b/src/blackmisc/range.h index 929f33ed9..ce2ce60a2 100644 --- a/src/blackmisc/range.h +++ b/src/blackmisc/range.h @@ -46,6 +46,9 @@ namespace BlackMisc template class CRangeBase { + using value_type = typename std::iterator_traits::value_type; + using const_reference = typename std::iterator_traits::reference; + public: /*! * Return a new container generated by applying some transformation function to all elements of this one. @@ -71,6 +74,30 @@ namespace BlackMisc inline auto findBy(K0 k0, V0 v0, KeysValues... keysValues) const -> CRange>; + /*! + * Return a reference to the first element for which a given predicate returns true. Undefined if there is none. + */ + template + const_reference findFirstBy(Predicate p) const { return findBy(p).front(); } + + /*! + * Return a reference to the first element matching some particular key/value pair(s). Undefined if there is none. + */ + template + const_reference findFirstBy(K key, V value) const { return findBy(key, value).front(); } + + /*! + * Return a copy of the first element for which a given predicate returns true, or a default value if there is none. + */ + template + value_type findFirstByOrDefault(Predicate p, const value_type &def = value_type{}) const { return findBy(p).frontOrDefault(def); } + + /*! + * Return a copy of the first element matching some particular key/value pair(s), or a default value if there is none. + */ + template + value_type findFirstByOrDefault(K key, V value, const value_type &def = value_type{}) const { return findBy(key, value).frontOrDefault(def); } + /*! * \brief Return true if there is an element for which a given predicate returns true. */ @@ -161,7 +188,7 @@ namespace BlackMisc //! @} //! Returns the element at the beginning of the range. Undefined if the range is empty. - const_reference front() const { return *begin(); } + const_reference front() const { Q_ASSERT(!empty()); return *begin(); } //! Returns the element at the beginning of the range, or a default value if the range is empty. const_reference frontOrDefault() const