From 691681356bf19ba112e7d332c07c986089ac16e4 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Wed, 4 May 2022 16:56:01 +0200 Subject: Added c_find_if, c_find_it macros: linear search in containers. Removed c_apply_cnt macro. --- docs/ccommon_api.md | 12 +++++++++--- include/stc/ccommon.h | 18 ++++++++++++++---- include/stc/cregex.h | 2 +- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/docs/ccommon_api.md b/docs/ccommon_api.md index 41a88065..6922bf3a 100644 --- a/docs/ccommon_api.md +++ b/docs/ccommon_api.md @@ -167,7 +167,7 @@ c_forrange (i, int, 30, 0, -5) printf(" %d", i); // 30 25 20 15 10 5 ``` -### c_apply, c_apply_arr, c_apply_cnt, c_pair +### c_apply, c_apply_arr, c_pair, c_find_if, c_find_it **c_apply** applies an expression on a container with each of the elements in the given array: ```c // apply multiple push_backs @@ -178,8 +178,14 @@ c_apply(v, cmap_i_insert(&map, c_pair(v)), cmap_i_raw, { {4, 5}, {6, 7} }); int arr[] = {1, 2, 3}; c_apply_arr(v, cvec_i_push_back(&vec, v), int, arr, c_arraylen(arr)); -// add keys from a map to a vec. -c_apply_cnt(v, cvec_i_push_back(&vec, v.first), cmap_i, map); +// find_if, find_it: linear search +int* v; +c_find_if (v, cvec_i, vec, *v == 2); +if (v) printf("%d\n", *v); + +cvec_i_iter it; +c_find_it (it, cvec_i, vec, *it.ref == 2); +cvec_i_erase_at(&vec, it); // assume found ``` ### c_new, c_alloc, c_alloc_n, c_drop, c_make diff --git a/include/stc/ccommon.h b/include/stc/ccommon.h index 6e4d9dff..d3749cf1 100644 --- a/include/stc/ccommon.h +++ b/include/stc/ccommon.h @@ -204,12 +204,22 @@ STC_INLINE char* c_strnstrn(const char *s, const char *needle, size_t slen, cons for (size_t index = 0, _c_n = n; index < _c_n; ++index) \ { _c_T *v = _c_arr + index; action; } \ } while (0) -#define c_apply_cnt(v, action, C, ...) do { \ +#define c_pair(v) (v).first, (v).second + +#define c_find_it(it, C, cnt, pred) do { \ size_t index = 0; \ - c_foreach (_it, C, __VA_ARGS__) \ - { C##_value* v = _it.ref; action; ++index; } \ + C##_iter _end = C##_end(&cnt); \ + for (it = C##_begin(&cnt); it.ref != _end.ref; C##_next(&it)) \ + if (pred) break; else ++index; \ +} while (0) + +#define c_find_if(vp, C, cnt, pred) do { \ + size_t index = 0; \ + C##_iter _it, _end = C##_end(&cnt); \ + for (_it = C##_begin(&cnt); _it.ref != _end.ref; C##_next(&_it)) \ + if (vp = _it.ref, pred) break; else ++index; \ + if (_it.ref == _end.ref) vp = NULL; \ } while (0) -#define c_pair(v) (v).first, (v).second #define c_drop(C, ...) do { \ C* _c_arr[] = {__VA_ARGS__}; \ diff --git a/include/stc/cregex.h b/include/stc/cregex.h index 7357d9d9..0a4508b7 100644 --- a/include/stc/cregex.h +++ b/include/stc/cregex.h @@ -31,7 +31,7 @@ THE SOFTWARE. * This is a extended version of regexp9, supporting UTF8 input, common * shorthand character classes, ++. */ -#include "csview.h" +#include "forward.h" // csview typedef enum { creg_nomatch = -1, -- cgit v1.2.3