Vector

This is a simple universal vector library for the C language that is useful in-case you need resizable arrays.


Creating a new vector

A new vector can be initialized using the vector_new method which allocates a new Vector and returns the pointer to it.

Vector* new_vec = vector_new();

Writing data to the vector

With our new Vector we can now push data to it. Our Vector requires the data to be a pointer to a void. This is due to there being no generic T in C and since a void pointer is able to hold any value we use that as a workaround.

vector_push(new_vec, (void*) "Hello world");

Retrieving data

Now that we know how to write data we need to know how to retrieve it. For this I have 2 methods. First is the index based method where you give in the index and try to find the value. Another method is to search by value which then returns the index. The last method is mainly meant for removing data and not retrieving it but can also be used.

// index-based 
// Since we know that "Hello world" will be our first value we can just search for the first index

char* hello_world = (char*)vector_get(new_vec, 0);
printf("%s", hello_world);
// value-based
// this is for retrieving the index in which the value is stored in
int hello_world = vector_search(new_vec, (void*)"Hello world");
printf("%d", hello_world); // This should return 0

Removing data

Removing data is really easy. It just requires you to know in which index the data is stored. We can use vector_search for that.

Vector* new_vec= vector_new();
vector_push(new_vec, (void*) "Hello world");

int hello_world = vector_search(new_vec, (void*)"Hello world");
println("%d\n", hello_world); // 0

vector_remove(new_vec, hello_world);

int check2 = vector_search(new_vec, (void*)"Hello world");
println("%d\n", check2); // -1 (not found)

Freeing the vector

Now since the vector was allocated using malloc we also need to manually free it. But for that there is also function which frees the data within the vector and the vector itself.

vector_free(new_vec);

Last updated