AK: Add first_matching and last_matching to Vector

first_matching returns the first item in the vector that matches
the given condition.

last_matching returns the last item in the vector that matches
the given condition.
This commit is contained in:
Luke 2020-11-21 18:12:35 +00:00 committed by Andreas Kling
parent 94ff04b536
commit 819f099a8e
Notes: sideshowbarker 2024-07-19 01:18:50 +09:00

View File

@ -336,6 +336,28 @@ public:
m_size += other.m_size;
}
template<typename Callback>
Optional<T> first_matching(Callback callback)
{
for (size_t i = 0; i < size(); ++i) {
if (callback(at(i))) {
return at(i);
}
}
return {};
}
template<typename Callback>
Optional<T> last_matching(Callback callback)
{
for (ssize_t i = size() - 1; i >= 0; --i) {
if (callback(at(i))) {
return at(i);
}
}
return {};
}
template<typename Callback>
bool remove_first_matching(Callback callback)
{