diff --git a/core/range.h b/core/range.h index 59dbf090d..561424079 100644 --- a/core/range.h +++ b/core/range.h @@ -82,4 +82,20 @@ public: } }; +// Find the index of an element in a range. Return -1 if not found +// Range must have a random access iterator. +template +int index_of(const Range &range, const Element &e) +{ + auto it = std::find(std::begin(range), std::end(range), e); + return it == std::end(range) ? -1 : it - std::begin(range); +} + +template +int index_of_if(const Range &range, Func f) +{ + auto it = std::find_if(std::begin(range), std::end(range), f); + return it == std::end(range) ? -1 : it - std::begin(range); +} + #endif diff --git a/qt-models/divepicturemodel.cpp b/qt-models/divepicturemodel.cpp index bab837201..9abd16192 100644 --- a/qt-models/divepicturemodel.cpp +++ b/qt-models/divepicturemodel.cpp @@ -242,10 +242,8 @@ int DivePictureModel::rowCount(const QModelIndex&) const int DivePictureModel::findPictureId(const std::string &filename) { - for (int i = 0; i < (int)pictures.size(); ++i) - if (pictures[i].filename == filename) - return i; - return -1; + return index_of_if(pictures, [&filename](const PictureEntry &p) + { return p.filename == filename; }); } static void addDurationToThumbnail(QImage &img, duration_t duration) diff --git a/qt-models/divetripmodel.cpp b/qt-models/divetripmodel.cpp index 39a8a0f62..e55d620df 100644 --- a/qt-models/divetripmodel.cpp +++ b/qt-models/divetripmodel.cpp @@ -1008,29 +1008,19 @@ void DiveTripModelTree::addDivesToTrip(int trip, const QVector &dives) int DiveTripModelTree::findTripIdx(const dive_trip *trip) const { - for (auto [i, item]: enumerated_range(items)) { - if (item.d_or_t.trip == trip) - return i; - } - return -1; + return index_of_if(items, [trip] (const Item &item) + { return item.d_or_t.trip == trip; }); } int DiveTripModelTree::findDiveIdx(const dive *d) const { - for (auto [i, item]: enumerated_range(items)) { - if (item.isDive(d)) - return i; - } - return -1; + return index_of_if(items, [d] (const Item &item) + { return item.isDive(d); }); } int DiveTripModelTree::findDiveInTrip(int tripIdx, const dive *d) const { - const Item &item = items[tripIdx]; - for (auto [i, dive]: enumerated_range(item.dives)) - if (dive == d) - return i; - return -1; + return index_of(items[tripIdx].dives, d); } int DiveTripModelTree::findInsertionIndex(const dive_trip *trip) const