Skip to content

Instantly share code, notes, and snippets.

@blakek
Forked from sshtmc/simple_c_vector.h
Last active December 26, 2015 14:09
Show Gist options
  • Save blakek/7163000 to your computer and use it in GitHub Desktop.
Save blakek/7163000 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "c_vector.h"
// Return the vector size
size_t vector_size(vector *v)
{
return v->size;
}
// Grow the vector to at least this size
void vector_grow(vector *v, size_t new_size)
{
while (v->capacity < new_size)
v->capacity *= 2;
v->data = realloc(v->data, sizeof(void*) *v->capacity);
assert(v->data);
// set all unused values to zero (potential performance hazard!)
// memset(v->data+v->size, 0, sizeof(void) * (v->capacity - v->size));
}
// APPEND an element to a vector, may grow the vector
void vector_append(vector *v, void *e)
{
// condition to increase v->data:
// last slot exhausted
if (v->size >= v->capacity)
vector_grow(v, v->capacity * 2);
v->data[v->size] = e;
v->size++;
}
// SET an element at index to 'e'
void vector_set(vector *v, size_t index, void *e)
{
if (index >= v->capacity) {
vector_grow(v, index);
return;
}
v->data[index] = e;
}
// GET an element at index
void *vector_get(vector *v, size_t index)
{
if (index >= v->size) {
return NULL;
}
return v->data[index];
}
// POPs an element at index; COSTLY OPERATION, AVOID IF POSSIBLE!
void *vector_pop(vector *v, size_t index)
{
if (index >= v->size)
return NULL;
void *ret = v->data[index];
size_t i, j;
void **newarr = (void**)malloc(sizeof(void*) * v->capacity);
for (i = 0, j = 0; i < v->size; i++) {
if (i == index)
continue;
// at one moment, when i>index, 'i' will get in front of 'j'
newarr[j] = v->data[i];
j++;
}
free(v->data);
v->data = newarr;
v->size--;
return ret;
}
// initialize the vector, give it some capacity an allocate space
void vector_init(vector *v)
{
v->size = 0;
v->capacity = 10;
v->data = calloc(sizeof(void*), v->capacity);
}
// release the vector
void vector_free(vector *v)
{
free(v->data);
}
#ifndef __C_VECTOR_H__
#define __C_VECTOR_H__
typedef struct vector_ {
void **data;
size_t size;
size_t capacity;
} vector;
// Return the vector size
size_t vector_size(vector *v);
// Grow the vector to at least this size
void vector_grow(vector *v, size_t new_size);
// APPEND an element to a vector, may grow the vector
void vector_append(vector *v, void *e);
// SET an element at index to 'e'
void vector_set(vector *v, size_t index, void *e);
// GET an element at index
void *vector_get(vector *v, size_t index);
// POPs an element at index; COSTLY OPERATION, AVOID IF POSSIBLE!
void *vector_pop(vector *v, size_t index);
// initialize the vector, give it some capacity an allocate space
void vector_init(vector *v);
// release the vector
void vector_free(vector *v);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment