Simple Vector is a C library that implements vectors (dynamically sized arrays). This library was made as a learning project to practice dynamically allocated memory (on the heap) and should probably not be used in production software. It is not type agnostic, and supports short, int, long, long long, float, double and char; it does not yet support strings.
Creating a vector:
Vector* vec = vec_create(T_SHORT);Each vector has a type, chosen when it's created. The values you pass in must have that same type. Passing a value of a different type is undefined behavior. Example:
Vector* ints = vec_create(T_INT);
int n = 42;
vec_push_back(ints, &n);Supported types are T_SHORT, T_INT, T_LONG, T_LONGLONG, T_FLOAT, T_DOUBLE, and T_CHAR.
Adding and reading values:
Vector* vec = vec_create(T_DOUBLE);
double a = 1.5, b = 2.5;
vec_push_back(vec, &a);
vec_push_back(vec, &b);
double* first = vec_at(vec, 0);
printf("%f\n", *first); /* 1.500000 */vec_at returns NULL if the index is out of range, so check the result before you read through it:
double* item = vec_at(vec, 10);
if (item == NULL) {
printf("no element at index 10\n");
}Inserting and removing:
double c = 0.5;
vec_insert(vec, 0, &c); /* puts 0.5 at the front */
vec_erase(vec, 1); /* removes the element at index 1 */
vec_pop_back(vec); /* removes the last element */Checking the size and state:
size_t count = vec_size(vec);
if (vec_empty(vec)) {
printf("the vector is empty\n");
}Clearing and freeing:
vec_clear(vec); /* removes all elements; the vector can still be used again */
vec_destroy(vec); /* frees the vector */Functions that can fail return 0 on success and 1 on failure:
vec_push_backfails ifdataisNULLor the vector can't grow.vec_insertfails ifposis greater than the length.vec_erasefails ifposis not less than the length.vec_pop_backfails on an empty vector.vec_createreturnsNULLon failure, including for an unknown type.vec_atreturnsNULLif the index is out of range.
Every vector from vec_create must be passed to vec_destroy exactly once.
The vector grows as you add elements. When an element is removed and the length is at most a quarter of the capacity, the capacity is halved, so the unused memory is returned.
A pointer from vec_at is only valid until the next call that changes the vector: vec_push_back, vec_insert, vec_erase, vec_pop_back, vec_clear, or vec_destroy. Those calls can move or free the buffer, so you should read the value again after changing the vector.