refs #414 Efficient findFirstBy methods in CRangeBase.

This commit is contained in:
Mathew Sutcliffe
2015-06-01 18:08:06 +01:00
parent ada03ee513
commit d8091df47d

View File

@@ -46,6 +46,9 @@ namespace BlackMisc
template <class Derived, class CIt>
class CRangeBase
{
using value_type = typename std::iterator_traits<CIt>::value_type;
using const_reference = typename std::iterator_traits<CIt>::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<Iterators::ConditionalIterator<CIt, decltype(BlackMisc::Predicates::MemberEqual(k0, v0, keysValues...))>>;
/*!
* Return a reference to the first element for which a given predicate returns true. Undefined if there is none.
*/
template <class Predicate>
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 <class K, class V>
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 <class Predicate>
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 <class K, class V>
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