-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.c
99 lines (88 loc) · 2.15 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdlib.h>
#include <stdio.h>
#include "vector.h"
struct vector * init_vector(){
struct vector *v = malloc(sizeof(struct vector));
v->size = 0;
v->capacity = 10;
v->values = malloc(sizeof(void *) * (v->capacity));
return v;
}
void resize_vector(struct vector * v, int capacity){
void **temp = realloc(v->values, sizeof(void *) * capacity);
if(temp){
v->values = temp;
v->capacity = capacity;
} else {
free(v->values);
printf("ERROR: REALLOC FOR VECTOR FAILED, EXITING");
return;
}
}
void add_vector(struct vector *v, void *p){
if(v->capacity == v->size){ // need resizing
resize_vector(v, v->capacity * 2 + 1);
}
v->values[v->size] = p;
v->size++;
}
void * remove_vector(struct vector *v){
v->size--;
return v->values[v->size];
}
void free_vector(struct vector *v){
for(int i = 0; i < v->size; ++i){
free(v->values[i]);
}
free(v->values);
free(v);
}
void * delete_vector(struct vector *v, int index){
void * copy = v->values[index];
if(index >= 0 && index < v->size){
for(int i = index; i < v->size - 1; i++){
v->values[i] = v->values[i+1];
}
free(v->values[--v->size]);
}
return copy;
}
struct intvector * init_intvector(){
struct intvector *v = malloc(sizeof(struct intvector));
v->size = 0;
v->capacity = 10;
v->values = malloc(sizeof(int) * (v->capacity));
return v;
}
void resize_intvector(struct intvector * v, int capacity){
int *temp = realloc(v->values, sizeof(int) * capacity);
if(temp){
v->values = temp;
v->capacity = capacity;
} else {
free(v->values);
printf("ERROR: REALLOC FOR INT VECTOR FAILED, EXITING");
return;
}
}
void add_intvector(struct intvector *v, int x){
if(v->capacity == v->size){ // need resizing
resize_intvector(v, v->capacity * 2 + 1);
}
v->values[v->size] = x;
v->size++;
}
int remove_intvector(struct intvector *v){
v->size--;
return v->values[v->size];
}
int delete_intvector(struct intvector *v, int index){
int copy = v->values[index];
if(index >= 0 && index < v->size){
for(int i = index; i < v->size - 1; i++){
v->values[i] = v->values[i+1];
}
v->size--;
}
return copy;
}