From a1d4279c40612e6f98564db43192929b41c59d40 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Fri, 3 Jul 2020 23:57:45 -0400 Subject: Add remove function for vectors Removes element at an index. --- collections/vector/vector.adoc | 31 ++++++++++++++++++++++++++++++- collections/vector/vector.c | 16 ++++++++++++++++ collections/vector/vector.h | 1 + 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index 9e61a43..d423c37 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.13, 2020-07-03 +v0.14, 2020-07-03 A basic vector, that hold pointers to your data structures. @@ -284,6 +284,35 @@ assert(str_cmp(vec_index(vector, 1), str3) == 0); assert(str_cmp(vec_index(vector, 2), str2) == 0); ---- +[[vec_remove]] ++void vec_remove(vec *self, int index)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Element at position +index+ of +self+ is removed from vector and the remaining +items are shifted towards the front. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" +#include + +char *str1 = "ONE"; +char *str2 = "TWO"; +char *str3 = "THREE"; + +vec *vector = vec_new(); +vec_push(vector, str_dup(str1)); +vec_push(vector, str_dup(str2)); +vec_push(vector, str_dup(str3)); + +vec_remove(vector, 1); + +assert(vec_size == 2); +assert(strcmp(vec_pop(vector), str3) == 0); +assert(strcmp(vec_pop(vector), str1) == 0); +---- + [[vec_swap]] +void vec_swap(vec *self, int i, int j)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/collections/vector/vector.c b/collections/vector/vector.c index 2ae748f..5c473a4 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -191,6 +191,22 @@ void *item; root->base[index] = item; } +void* vec_remove(root, index) +vec *root; +int index; +{ + void *tmp; + + if (!root || index > root->end || index < 0) + return NULL; + + tmp = vec_index(root, index); + memmove(root->base + index, root->base + index + 1, + (--root->end - index) * sizeof(void*)); + + return tmp; +} + void vec_swap(root, i, j) vec *root; int i,j; diff --git a/collections/vector/vector.h b/collections/vector/vector.h index 1b47642..083a1d0 100644 --- a/collections/vector/vector.h +++ b/collections/vector/vector.h @@ -22,6 +22,7 @@ void vec_set(vec*, int, void*); void* vec_index(vec*, int); void vec_insert(vec*, int, void*); +void* vec_remove(vec*, int); void vec_swap(vec*, int, int); void* vec_swap_pop(vec*, int); -- cgit v1.1