From c176525f13bfcea8649d9e987bdff0dc45a56bf7 Mon Sep 17 00:00:00 2001 From: Giuseppe D'Angelo Date: Fri, 16 Oct 2020 18:46:21 +0200 Subject: Sequential general purpose containers: add erase/erase_if This is refactor/revisit for Qt 6 of the original commit [1] by Marc, limited to QList and QVLA. [1] see 11aa9a2276ba5367adbbd96d0ba13111d58145f8 [ChangeLog][QtCore][QList] Added erase() and erase_if(), for consistent container erasure. Added removeIf() as a method, complementing removeOne() / removeAll(). [ChangeLog][QtCore][QVarLengthArray] Added erase() and erase_if(), for consistent container erasure. Added removeIf() as a method, complementing removeOne() / removeAll(). Change-Id: I2499504e221431ead754dd64cc8a4d4e9f116183 Done-by: Marc Mutz Reviewed-by: Andrei Golubev Reviewed-by: Lars Knoll --- src/corelib/tools/qlist.h | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'src/corelib/tools/qlist.h') diff --git a/src/corelib/tools/qlist.h b/src/corelib/tools/qlist.h index 517ba10326..1626dd27ed 100644 --- a/src/corelib/tools/qlist.h +++ b/src/corelib/tools/qlist.h @@ -502,33 +502,21 @@ public: template qsizetype removeAll(const AT &t) { - const const_iterator ce = this->cend(), cit = std::find(this->cbegin(), ce, t); - if (cit == ce) - return 0; - qsizetype index = cit - this->cbegin(); - - // Next operation detaches, so ce, cit may become invalidated. - // Moreover -- unlike std::erase -- we do support the case where t - // belongs to this list, so we have to save it from invalidation - // by taking a copy. This is made slightly more complex by the fact - // that t might not be copiable (in which case it certainly does not - // belong to this list), in which case we just use the original. - using CopyProxy = std::conditional_t, AT, const AT &>; - const AT &tCopy = CopyProxy(t); - const iterator e = end(), it = std::remove(begin() + index, e, tCopy); - const qsizetype result = std::distance(it, e); - d->truncate(d->size - result); - return result; + return QtPrivate::sequential_erase_with_copy(*this, t); } + template bool removeOne(const AT &t) { - const qsizetype i = indexOf(t); - if (i < 0) - return false; - remove(i); - return true; + return QtPrivate::sequential_erase_one(*this, t); + } + + template + qsizetype removeIf(Predicate pred) + { + return QtPrivate::sequential_erase_if(*this, pred); } + T takeAt(qsizetype i) { T t = std::move((*this)[i]); remove(i); return t; } void move(qsizetype from, qsizetype to) { @@ -932,6 +920,18 @@ size_t qHash(const QList &key, size_t seed = 0) return qHashRange(key.cbegin(), key.cend(), seed); } +template +qsizetype erase(QList &list, const AT &t) +{ + return QtPrivate::sequential_erase(list, t); +} + +template +qsizetype erase_if(QList &list, Predicate pred) +{ + return QtPrivate::sequential_erase_if(list, pred); +} + QList QStringView::toUcs4() const { return QtPrivate::convertToUcs4(*this); } QT_END_NAMESPACE -- cgit v1.2.3