-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.c
More file actions
60 lines (53 loc) · 1.37 KB
/
vector.c
File metadata and controls
60 lines (53 loc) · 1.37 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
#include "vector.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
Vector vector_init(size_t initial_capacity) {
Vector vec = {.data = malloc(initial_capacity * sizeof(char)),
.size = 0,
.allocate_size = initial_capacity};
return vec;
}
void vector_push(Vector *vec, char data) {
// Prevents overflow while keeping the list growable
if (vec->size == vec->allocate_size) {
vec->allocate_size *= 2;
vec->data = realloc(vec->data, (vec->allocate_size * sizeof(char)));
}
vec->data[vec->size++] = data;
}
void vector_free(Vector *vec) {
free(vec->data);
vec->size = vec->allocate_size = 0;
vec->data = NULL;
}
char vector_pop(Vector *vec, size_t position) {
if (position < vec->size) {
char res = vec->data[position];
vec->data[position] = 0;
vector_resize(vec);
return res;
} else {
return 0;
}
}
void vector_replace(Vector *vec, size_t position, char value) {
if (position < vec->size) {
vec->data[position] = value;
}
}
void vector_resize(Vector *vec) {
size_t temp_size = vec->size;
for (int i = 0; i < temp_size; i++) {
if (vec->data[i] == 0) {
vec->data[i] = vec->data[i + 1];
for (int j = i; j < temp_size; j++) {
if (vec->data[j + 1] == 0) {
break;
}
vec->data[j] = vec->data[j + 1];
}
vec->size = temp_size - 1;
}
}
}