From 1a41fe605ab6bde15f622e72abb7aee846531fcf Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Fri, 3 Jul 2020 01:18:17 -0400 Subject: Add swap_pop function for vectors --- collections/vector/vector.adoc | 30 +++++++++++++++++++++++++++++- collections/vector/vector.c | 14 ++++++++++++++ collections/vector/vector.h | 1 + 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index cc83375..ee453ff 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.11, 2020-07-03 +v0.12, 2020-07-03 A basic vector, that hold pointers to your data structures. @@ -283,6 +283,34 @@ assert(str_cmp(vec_index(vector, 0), str2) == 0); assert(str_cmp(vec_back(vector), str1) == 0); ---- +[[vec_swap_pop]] ++void* vec_swap_pop(vec *self, int index)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Swaps back element with item at +index+, and pops item now at back. +Will return same element as +vec_remove(self, index)+. +Does not keep order of elements, but faster that <>. + +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)); + +assert(str_cmp(vec_swap_pop(vector, 2), str3) == 0); +assert(str_cmp(vec_back(vector, str2) == 0); +assert(vec_size == 2); +---- + [[vec_clear]] +void vec_clear(vec *self)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/collections/vector/vector.c b/collections/vector/vector.c index a7e0845..9ae30c7 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -190,6 +190,20 @@ int i,j; return; } +void* vec_swap_pop(root, i) +vec *root; +int i; +{ + void *tmp; + int j; + + if (!root || i >= root->end || i < 0 || root->end <= 0) + return NULL; + + vec_swap(root, i, root->end - 1); + return vec_pop(root); +} + void vec_clear(root) vec *root; { diff --git a/collections/vector/vector.h b/collections/vector/vector.h index 2b1e8e9..55e9481 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_swap(vec*, int, int); +void* vec_swap_pop(vec*, int); /*memory*/ -- cgit v1.1