-
Notifications
You must be signed in to change notification settings - Fork 101
/
vector.c
72 lines (58 loc) · 1.36 KB
/
vector.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <stdlib.h>
#include "vector.h"
void vector_init(vector *v)
{
v->capacity = VECTOR_INIT_CAPACITY;
v->total = 0;
v->items = malloc(sizeof(void *) * v->capacity);
}
int vector_total(vector *v)
{
return v->total;
}
static void vector_resize(vector *v, int capacity)
{
#ifdef DEBUG_ON
printf("vector_resize: %d to %d\n", v->capacity, capacity);
#endif
void **items = realloc(v->items, sizeof(void *) * capacity);
if (items) {
v->items = items;
v->capacity = capacity;
}
}
void vector_add(vector *v, void *item)
{
if (v->capacity == v->total)
vector_resize(v, v->capacity * 2);
v->items[v->total++] = item;
}
void vector_set(vector *v, int index, void *item)
{
if (index >= 0 && index < v->total)
v->items[index] = item;
}
void *vector_get(vector *v, int index)
{
if (index >= 0 && index < v->total)
return v->items[index];
return NULL;
}
void vector_delete(vector *v, int index)
{
if (index < 0 || index >= v->total)
return;
v->items[index] = NULL;
for (int i = index; i < v->total - 1; i++) {
v->items[i] = v->items[i + 1];
v->items[i + 1] = NULL;
}
v->total--;
if (v->total > 0 && v->total == v->capacity / 4)
vector_resize(v, v->capacity / 2);
}
void vector_free(vector *v)
{
free(v->items);
}