diff options
author | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-22 06:08:52 +0000 |
---|---|---|
committer | Aryadev Chavali <aryadev@aryadevchavali.com> | 2021-11-22 06:08:52 +0000 |
commit | ab5d1c699755f51192d5cab00bf0e601032018b3 (patch) | |
tree | 69cd5a48fb81aaa6b69a6bb4ec43478801c022f4 | |
parent | 1d91eb52b619c15d0ae927730e464616a08137f2 (diff) | |
download | algorithms-ab5d1c699755f51192d5cab00bf0e601032018b3.tar.gz algorithms-ab5d1c699755f51192d5cab00bf0e601032018b3.tar.bz2 algorithms-ab5d1c699755f51192d5cab00bf0e601032018b3.zip |
(list)+filter function
This generates a new list, and appends to it every time the current
list value satisfies the condition. It then recursively calls the
filter on the next value.
-rw-r--r-- | list.cpp | 10 |
1 files changed, 10 insertions, 0 deletions
@@ -76,6 +76,16 @@ T reduce(List<T> *lst, T (*reducer) (T, T), T init = 0) } template <typename T> +List<T> *filter(List<T> *lst, bool (*f)(T), List<T> *new_lst = nullptr) +{ + if (!lst) + return new_lst; + if (f(lst->value)) + new_lst = append(new_lst, lst->value); + return filter(lst->next, f, new_lst); +} + +template <typename T> std::ostream& operator<<(std::ostream& ostream, const List<T> *lst) { if (!lst) |