From bc3fa890bdc0cdc108df212ebcc5837e79ed689a Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Sun, 15 Jul 2018 10:48:22 +0200 Subject: [PATCH] Add method _find_if. --- m-algo.h | 21 ++++++++++++++++----- tests/test-malgo.c | 6 ++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/m-algo.h b/m-algo.h index 1553b54e..f94e6e5e 100644 --- a/m-algo.h +++ b/m-algo.h @@ -92,7 +92,7 @@ \ /* It supposes that the container is not sorted */ \ static inline void \ - M_C(name, _find) (it_t it, container_t l, const type_t data) \ + M_C(name, _find) (it_t it, container_t l, type_t const data) \ { \ for (M_GET_IT_FIRST cont_oplist (it, l); \ !M_GET_IT_END_P cont_oplist (it) ; \ @@ -103,19 +103,30 @@ } \ \ static inline bool \ - M_C(name, _contains) (container_t l, const type_t data) \ + M_C(name, _contains) (container_t l, type_t const data) \ { \ it_t it; \ M_C(name,_find)(it, l, data); \ return !M_GET_IT_END_P cont_oplist (it); \ } \ \ + static inline void \ + M_C(name, _find_if) (it_t it, container_t l, bool (*func)(type_t const)) \ + { \ + for (M_GET_IT_FIRST cont_oplist (it, l); \ + !M_GET_IT_END_P cont_oplist (it) ; \ + M_GET_IT_NEXT cont_oplist (it)) { \ + if (func (*M_GET_IT_CREF cont_oplist (it))) \ + return ; \ + } \ + } \ + \ /* For the definition of _find_last, if the methods \ PREVIOUS & IT_LAST are defined, then search backwards */ \ M_IF_METHOD2(PREVIOUS, IT_LAST, cont_oplist) \ ( \ static inline void \ - M_C(name, _find_last) (it_t it, container_t l, const type_t data) \ + M_C(name, _find_last) (it_t it, container_t l, type_t const data) \ { \ for (M_GET_IT_LAST cont_oplist (it, l); \ !M_GET_IT_END_P cont_oplist (it) ; \ @@ -128,7 +139,7 @@ , \ /* Otherwise search forward, but don't stop on the first occurence */ \ static inline void \ - M_C(name, _find_last) (it_t it, container_t l, const type_t data) \ + M_C(name, _find_last) (it_t it, container_t l, type_t const data) \ { \ M_GET_IT_END cont_oplist (it, l); \ it_t it2; \ @@ -143,7 +154,7 @@ ) /* End of alternative of _find_last */ \ \ static inline size_t \ - M_C(name, _count) (container_t l, const type_t data) \ + M_C(name, _count) (container_t l, type_t const data) \ { \ it_t it; \ size_t count = 0; \ diff --git a/tests/test-malgo.c b/tests/test-malgo.c index 8d2ecbfa..522bd890 100644 --- a/tests/test-malgo.c +++ b/tests/test-malgo.c @@ -131,6 +131,12 @@ static void test_list(void) algo_list_find_last (it2, l, 3); assert (!list_int_end_p (it2)); assert (!list_int_it_equal_p(it1, it2)); + + algo_list_find_if(it1, l, func_test_101); + assert (list_int_end_p (it1)); + algo_list_find_if(it1, l, func_test_42); + assert (!list_int_end_p (it1)); + assert (*list_int_cref(it1) == 42); for(int i = -100; i < 100; i+=2) list_int_push_back (l, i);