utils: implement integer vector

This commit is contained in:
2025-04-02 12:31:05 +02:00
parent 0f0fa04661
commit 98a26c71f3
2 changed files with 106 additions and 0 deletions

80
src/utils/vector.c Normal file
View File

@@ -0,0 +1,80 @@
#include "vector.h"
#include <stdio.h>
#include <stdlib.h>
void vector_init(Vector **v, int capacity) {
*v = malloc(sizeof(Vector));
if (!*v) {
printf("vector_init: failed to allocate vector pointer\n");
return;
}
(*v)->data = malloc(capacity * sizeof(int));
if (!(*v)->data) {
printf("vector_init: failed to allocate data\n");
return;
}
(*v)->size = 0;
(*v)->_capacity = capacity;
}
Vector *vector_new(void) {
Vector *v;
vector_init(&v, VEC_MIN);
return v;
}
void vector_grow(Vector *v) {
v->_capacity <<= 1;
v->data = realloc(v->data, sizeof(int) * v->_capacity);
if (!v->data) {
printf("vector_grow: failed to allocate data\n");
return;
}
}
void vector_push(Vector *v, int val) {
if (v->size >= v->_capacity) {
vector_grow(v);
}
v->data[v->size] = val;
v->size++;
}
void vector_pusha(Vector *v, int *vals, int n) {
for (int i = 0; i < n; i++) {
int val = vals[i];
vector_push(v, val);
}
}
int vector_pop(Vector *v) {
int val = v->data[v->size - 1];
v->size--;
return val;
}
void vector_free(Vector *v) {
free(v->data);
v->size = 0;
v->_capacity = 0;
free(v);
}
void vector_print(Vector v) {
printf("vector_print: ");
for (int i = 0; i < v.size; i++) {
printf("%d ", v.data[i]);
}
printf("\n");
}
int main(int argc, char *argv[]) {
Vector *v = vector_new();
vector_push(v, 20);
vector_pusha(v, (int[]){1, 2, 3}, 3);
vector_print(*v);
printf("oops, i removed %d\n", vector_pop(v));
vector_print(*v);
vector_free(v);
return 0;
}

26
src/utils/vector.h Normal file
View File

@@ -0,0 +1,26 @@
#ifndef VECTOR_H
#define VECTOR_H
#define VEC_MIN 8
typedef struct {
int *data;
int size;
int _capacity;
} Vector;
void vector_init(Vector **v, int capacity);
Vector *vector_new(void);
void vector_grow(Vector *v);
void vector_push(Vector *v, int val);
int vector_pop(Vector *v);
void vector_free(Vector *v);
void vector_print(Vector v);
#endif // VECTOR_H