From b253b373ea74539a0f29a88ac2be728aa8158d2a Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Fri, 3 Jul 2020 00:57:58 -0400 Subject: Add set index function for vectors --- collections/vector/vector.adoc | 26 +++++++++++++++++++++++++- collections/vector/vector.c | 11 +++++++++++ collections/vector/vector.h | 1 + 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index d439c85..0409b05 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.9, 2020-07-03 +v0.10, 2020-07-03 A basic vector, that hold pointers to your data structures. @@ -208,6 +208,30 @@ vec_push(vector, str_dup(str2)); assert(strcmp(vec_back(vector), str2) == 0); ---- +[[vec_set]] ++void vec_set(vec *self, int index, void *item)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Sets the element at position +index+ in +self+ to +item+. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" +#include + +char *str1 = "ONE"; +char *str2 = "TWO"; + +vec *vector = vec_new(); +vec_push(vector, str_dup(str1)); +vec_push(vector, str_dup(str2)); + +vec_set(vector, 0, str2); + +assert(str_cmp(vec_pop(vector), str2) == 0); +assert(str_cmp(vec_pop(vector), str2) == 0); +---- [[vec_index]] +void* vec_index(vec *self, int index)+ diff --git a/collections/vector/vector.c b/collections/vector/vector.c index 0b816b7..5cb56ef 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -152,6 +152,17 @@ vec *root; return root->base[root->end - 1]; } +void vec_set(root, index, item) +vec *root; +int index; +void *item; +{ + if (!root || index >= root->end || index < 0) + return; + + root->base[index] = item; +} + void* vec_index(root, index) vec *root; int index; diff --git a/collections/vector/vector.h b/collections/vector/vector.h index f1eea64..7d38694 100644 --- a/collections/vector/vector.h +++ b/collections/vector/vector.h @@ -18,6 +18,7 @@ void vec_push(vec*, void*); void* vec_pop(vec*); void* vec_back(vec*); +void vec_set(vec*, int, void*); void* vec_index(vec*, int); /*memory*/ -- cgit v1.1