Skip to content

Instantly share code, notes, and snippets.

@quanta-kt
Created November 19, 2024 17:14
Show Gist options
  • Save quanta-kt/aa165366a671421dd9ead577509009e3 to your computer and use it in GitHub Desktop.
Save quanta-kt/aa165366a671421dd9ead577509009e3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
struct vec {
int* mem;
size_t count;
size_t capacity;
};
struct vec make_vec() {
struct vec v;
v.mem = NULL;
v.count = 0;
v.capacity = 0;
return v;
}
void vec_add(struct vec* v, int i) {
if (v->count + 1 > v->capacity) {
v->capacity = v->capacity == 0 ? 1 : v->capacity * 2;
v->mem = realloc(v->mem, sizeof(int) * v->capacity);
}
v->mem[v->count++] = i;
}
void vec_remove(struct vec* v, int i) {
int* dest = v->mem + i;
int* src = v->mem + i + 1;
memmove(dest, src, sizeof(int) * v->count - i - 1);
v->count--;
}
int main() {
struct vec v = make_vec();
vec_add(&v, 1);
vec_add(&v, 2);
// remove
vec_add(&v, 3);
vec_add(&v, 4);
vec_add(&v, 5);
vec_remove(&v, 2);
for (size_t i = 0; i < v.count; i++) {
printf("%d\n", v.mem[v.count - i - 1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment