implemented push based on index and push front

This commit is contained in:
Warwick 2024-02-08 11:03:17 +00:00
parent f67f79bc1f
commit 4be7bff040
3 changed files with 32 additions and 15 deletions

View file

@ -6,10 +6,13 @@
int main() {
vector *vec = vec_create(sizeof(int));
for (int x = 0; x < 1000; x++) {
vec_pushback(vec, &x);
for (int x = 0; x < 10; x++) {
vec_push_back(vec, &x);
}
for (int x = 0; x < 1000; x++) {
int i = 99999999;
vec_push_index(vec, &i, 5);
vec_push_front(vec, &i);
for (int x = 0; x < 12; x++) {
printf("%d ",*(int*)vec_get(vec, x));
}
printf("\n");

View file

@ -1,6 +1,5 @@
#include "vec.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -29,32 +28,44 @@ void vec_destroy(vector *vec) {
void vec_grow(vector *vec) {
assert(vec != NULL);
printf("capacity: %zu\n", vec->capacity);
if (vec->size < vec->capacity)
return;
// Grow the vector by half
vec->capacity += vec->capacity / 2;
printf("new capacity: %zu\n", vec->capacity);
vec->elements = reallocarray(vec->elements, vec->capacity, vec->element_size);
assert(vec->elements != NULL);
}
void vec_pushback(vector *vec, void *data) {
void vec_push_back(vector *vec, void *data) {
assert(vec != NULL);
vec_grow(vec);
printf("mem start: %p\n", vec->elements);
printf("mem end: %p\n", vec->elements + (vec->size * vec->element_size));
printf("number of elements: %zu\n", vec->size);
printf("element size: %zu\n\n", vec->element_size);
memcpy(vec->elements + (vec->size * vec->element_size), data,
vec->element_size);
vec->size++;
}
void vec_push_front(vector *vec, void *data) { vec_push_index(vec, data, 0); }
void vec_push_index(vector *vec, void *data, uint index) {
assert(vec != NULL);
assert(index <= vec->size);
// TODO: handle wraparound
vec_grow(vec);
memcpy(vec->elements + (index + 1) * vec->element_size,
vec->elements + index * vec->element_size,
(vec->size - index) * vec->element_size);
memcpy(vec->elements + (index * vec->element_size), data, vec->element_size);
vec->size++;
}
void *vec_get(vector *vec, uint index) {
// TODO: handle wraparound
assert(vec != NULL);
assert(index <= vec->size);
return vec->elements + index * vec->element_size;
}

View file

@ -11,5 +11,8 @@ void vec_grow(vector *vec);
// Assumes data is the same size as the element size
// Which means you can only push one element at a time
void vec_pushback(vector *vec, void *data);
void vec_push_back(vector *vec, void *data);
void vec_push_front(vector *vec, void *data);
void vec_push_index(vector *vec, void *data, uint index);
void* vec_get(vector *vec, uint index);