diff options
-rw-r--r-- | da.h | 14 |
1 files changed, 13 insertions, 1 deletions
@@ -14,7 +14,9 @@ * You should include ‘err.h’ and ‘stdlib.h’ along with this file. If you want * to use da_remove(), include ‘string.h’. The da_remove() macro also doesn’t * bother with shrinking your array when the length is far lower than the - * capacity. If you care about that, do it yourself. + * capacity. If you care about that, do it yourself. To use the da_foreach() + * macro, you need to have ptrdiff_t defined; to be absolutely sure you can + * include ‘stddef.h’. * * Remember to call free() on your dynamic arrays ‘buf’ field after use. * @@ -27,6 +29,8 @@ * da_append(a, x) Append the item ‘x’ to the array * da_remove(a, x) Remove the item ‘x’ from the array * da_remove_range(a, x, y) Remove the items between the range [x, y) + * da_foreach(a, t, i) Iterate the pointer ‘i’ of type ‘t’ over each + * element of the array. * * The ‘da_append()’ macro will by default double the arrays capacity when it * gets full. If you would like to use a different growth factor instead of 2, @@ -50,6 +54,11 @@ * da_append(&nums, 1337); * da_append(&nums, 420); * + * da_foreach (&nums, int *, n) { + * int x = *n << 1; + * printf("n = %d; n² = %d\n", *n, x); + * } + * * // Remove 1337 and 420 from nums * da_remove_range(&nums, 1, 3); * @@ -94,4 +103,7 @@ (a)->len -= j - i; \ } while (0) +#define da_foreach(a, t, i) \ + for (t i = (a)->buf; i - (a)->buf < (ptrdiff_t)(a)->len; i++) + #endif /* !MANGO_DA_H */ |