From 7842838516e232ce84154c6b9b7f3314962706f9 Mon Sep 17 00:00:00 2001 From: Abivarman <abivarman.kandiah@etu.hesge.ch> Date: Wed, 23 Feb 2022 13:56:06 +0100 Subject: [PATCH] Add pop function --- header/vectors.h | 1 + src/test_vectors.c | 7 +++++++ src/vectors.c | 19 ++++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/header/vectors.h b/header/vectors.h index 257dc2f..09fdbc8 100644 --- a/header/vectors.h +++ b/header/vectors.h @@ -22,5 +22,6 @@ typedef struct vector_* vector; vector vector_create(); int vector_length(vector vec); void vector_push(vector vec, type element); +type vector_pop(vector vec); #endif \ No newline at end of file diff --git a/src/test_vectors.c b/src/test_vectors.c index 3e181f1..8d0e78a 100644 --- a/src/test_vectors.c +++ b/src/test_vectors.c @@ -19,5 +19,12 @@ int main() vector_push(test, 15); printf("Modified Vector lenght : %d \n", vector_length(test)); + + type val = vector_pop(test); + + printf("Modified Vector lenght : %d and the value we popped : %d \n", vector_length(test), val); + + + return 0; } \ No newline at end of file diff --git a/src/vectors.c b/src/vectors.c index 1440087..a19854c 100644 --- a/src/vectors.c +++ b/src/vectors.c @@ -39,7 +39,7 @@ void vector_push(vector vec, type element) { vec->content = realloc(vec->content, sizeof(type) * vec->capacity * 2); assert(vec->content != NULL); - + vec->capacity = vec->capacity * 2; } @@ -47,3 +47,20 @@ void vector_push(vector vec, type element) vec->length++; } +type vector_pop(vector vec) +{ + assert(vec->length > 0); + + vec->length--; + type tmp = vec->content[vec->length]; + + if(vec->length < (vec->capacity / 4)) + { + vec->content = realloc(vec->content, sizeof(type) * (vec->capacity / 2)); + assert(vec->content != NULL); + + vec->capacity = vec->capacity / 2; + } + + return tmp; +} \ No newline at end of file -- GitLab