-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.c
161 lines (137 loc) · 2.47 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include <stdint.h>
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
#include "vector.h"
vector createVector(size_t size)
{
vector new_vector;
if(size > 0)
{
new_vector.data = malloc(sizeof(int) * size);
if(new_vector.data != NULL)
{
new_vector.capacity = size;
}
else
{
fprintf(stderr, "bad alloc");
exit(1);
}
}
else
{
new_vector.data = NULL;
new_vector.capacity = 0;
}
new_vector.size = 0;
return new_vector;
}
void reserve(vector *v, size_t newCapacity)
{
int *new_data;
if(newCapacity > 0)
{
new_data = malloc(sizeof(int) * newCapacity);
if(new_data == NULL)
{
fprintf(stderr, "bad alloc");
exit(1);
}
// ðàçìåð áîëüøå
if(v->capacity < newCapacity)
{
memcpy(new_data, v->data, v->capacity * sizeof(int));
}
else
{
memcpy(new_data, v->data, newCapacity * sizeof(int));
}
v->capacity = newCapacity;
if(v->data != NULL)
{
free(v->data);
}
v->data = new_data;
}
else
{
free(v->data);
v->data = NULL;
v->size = 0;
v->capacity = 0;
}
}
void clear(vector *v)
{
v->size = 0;
}
void shrinkToFit(vector *v)
{
v->capacity = v->size;
}
void deleteVector(vector *v)
{
free(v->data);
v->data = 0;
v->size = 0;
v->capacity = 0;
}
bool isEmpty(vector *v)
{
return v->size == 0;
}
bool isFull(vector *v)
{
return v->size == v->capacity;
}
int getVectorValue(vector *v, size_t i)
{
return v->data[i];
}
void pushBack(vector *v, int x)
{
if(v->size == v->capacity) // íåò ìåñòà
{
if(v->capacity == 0)
{
reserve(v, 1);
}
else
{
reserve(v, v->capacity * 2);
}
}
v->data[v->size] = x;
v->size++;
}
void popBack(vector *v)
{
if(v->size == 0)
{
fprintf(stderr, "bad alloc");
exit(1);
}
v->size--;
}
int* atVector(vector *v, size_t index)
{
if(index >= v->size)
{
fprintf(stderr, "IndexError: v->data[index] does not exist");
exit(1);
}
else
{
return &(v->data[index]);
}
}
int* back(vector *v)
{
return &(v->data[v->size - 1]);
}
int* front(vector *v)
{
return &(v->data[0]);
}