-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvector.c
More file actions
78 lines (70 loc) · 4.54 KB
/
vector.c
File metadata and controls
78 lines (70 loc) · 4.54 KB
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
73
74
75
76
77
78
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define DEF_VECTOR(vec_t, elm_t) \
typedef struct \
{ \
elm_t *content; \
size_t size; \
size_t capacity; \
} vec_t; \
\
static vec_t vec_t##_new() \
{ \
vec_t v = {NULL, 0, 0}; \
return v; \
} \
\
static void vec_t##_delete(vec_t self) { free(self.content); } \
\
static size_t vec_t##_size(const vec_t *self) { return self->size; } \
\
static size_t vec_t##_capacity(const vec_t *self) \
{ \
return self->capacity; \
} \
\
static void vec_t##_reserve(vec_t *self, size_t size) \
{ \
if (size <= self->capacity) \
return; \
\
self->capacity = self->capacity > 0 ? self->capacity * 2 : 4; \
while (size > self->capacity) \
self->capacity *= 2; \
\
self->content = \
(elm_t *)realloc(self->content, sizeof(elm_t) * self->capacity); \
} \
\
static elm_t *vec_t##_get(vec_t *self, size_t idx) \
{ \
return &self->content[idx]; \
} \
\
static void vec_t##_push(vec_t *self, elm_t val) \
{ \
vec_t##_reserve(self, self->size + 1); \
self->content[self->size] = val; \
++self->size; \
} \
\
static elm_t vec_t##_pop(vec_t *self) \
{ \
--self->size; \
return self->content[self->size]; \
}
DEF_VECTOR(IntVec, int)
int main()
{
IntVec v = IntVec_new();
for (int i = 0; i < 20; ++i)
IntVec_push(&v, i);
assert(IntVec_pop(&v) == 19);
assert(IntVec_capacity(&v) >= 19);
size_t size = IntVec_size(&v);
assert(size == 19);
for (size_t i = 0; i < size; ++i)
assert((int)i == *IntVec_get(&v, i));
IntVec_delete(v);
}