Zrythm v2.0.0-DEV
a highly automated and intuitive digital audio workstation
Loading...
Searching...
No Matches
collections.h
1// SPDX-FileCopyrightText: © 2024 Alexandros Theodotou <alex@zrythm.org>
2// SPDX-License-Identifier: LicenseRef-ZrythmLicense
3
4#pragma once
5
6#include <iterator>
7#include <type_traits>
8#include <vector>
9
10namespace zrythm::utils::collections
11{
12
13// Find the nth next occurrence matching predicate in [current+1, sentinel)
14template <std::forward_iterator Iter, typename Pred>
15 requires std::invocable<Pred, std::iter_reference_t<Iter>>
16Iter
17find_next_occurrence (Iter current, Iter sentinel, Pred pred, int n = 1)
18{
19 if (n < 1 || current == sentinel)
20 return sentinel; // Early exit for invalid params
21
22 for (Iter it = std::next (current); it != sentinel; ++it)
23 {
24 if (pred (*it) && --n == 0)
25 {
26 return it;
27 }
28 }
29 return sentinel;
30}
31
32// Find the nth previous occurrence matching predicate in [begin, current)
33template <std::bidirectional_iterator Iter, typename Pred>
34 requires std::invocable<Pred, std::iter_reference_t<Iter>>
35Iter
36find_prev_occurrence (Iter current, Iter begin, Pred pred, int n = 1)
37{
38 if (n < 1 || current == begin)
39 return begin; // Early exit for invalid params
40
41 Iter it = current;
42 do
43 {
44 --it;
45 if (pred (*it) && --n == 0)
46 {
47 return it;
48 }
49 }
50 while (it != begin);
51
52 return begin;
53}
54
55}; // namespace zrythm::utils::collections