Added a function to return the data from the vector.

This commit is contained in:
Warwick 2024-02-08 10:30:21 +00:00
parent d8f50ed1dc
commit f67f79bc1f
3 changed files with 22 additions and 14 deletions

View file

@ -6,9 +6,13 @@
int main() {
vector *vec = vec_create(sizeof(int));
for (int x = 0; x < 100; x++) {
for (int x = 0; x < 1000; x++) {
vec_pushback(vec, &x);
}
for (int x = 0; x < 1000; x++) {
printf("%d ",*(int*)vec_get(vec, x));
}
printf("\n");
vec_destroy(vec);
// if (SDL_Init(SDL_INIT_VIDEO) < 0) {

View file

@ -27,6 +27,20 @@ void vec_destroy(vector *vec) {
free(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) {
assert(vec != NULL);
vec_grow(vec);
@ -41,17 +55,6 @@ void vec_pushback(vector *vec, void *data) {
vec->size++;
}
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_get(vector *vec, uint index){
return vec->elements + index * vec->element_size;
}

View file

@ -12,3 +12,4 @@ 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_get(vector *vec, uint index);