forked from jean553/c-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.c
107 lines (89 loc) · 1.52 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
#include <stdio.h>
#include <stdlib.h>
#include "vector.h"
#define DEFAULT_CAPACITY 4
/**
*
*/
Vector create()
{
Vector vector;
vector.length = 0;
vector.capacity = DEFAULT_CAPACITY;
vector.array = (int*) malloc(sizeof(int) * vector.capacity);
for (
size_t i = 0;
i < vector.capacity;
i += 1
)
{
vector.array[i] = 0;
}
return vector;
}
/**
*
*/
void insertAtTheEnd(
Vector* const vector,
int data
)
{
if (vector->length == vector->capacity) {
vector->capacity += DEFAULT_CAPACITY;
vector->array = (int*) realloc(
vector->array,
sizeof(int) * vector->capacity
);
}
vector->array[vector->length] = data;
vector->length += 1;
}
/**
*
*/
int at(
const Vector* const vector,
const size_t index
)
{
return vector->array[index];
}
/**
*
*/
void insertAt(
Vector* const vector,
const size_t index,
const int data
)
{
if (vector->length == vector->capacity) {
vector->capacity += DEFAULT_CAPACITY;
vector->array = (int*) realloc(
vector->array,
sizeof(int) * vector->capacity
);
}
for (
size_t i = vector->length;
i > index;
i -= 1
)
{
vector->array[i] = vector->array[i - 1];
}
vector->array[index] = data;
vector->length += 1;
}
/**
*
*/
void updateAt(
Vector* const vector,
const size_t index,
const int data
)
{
vector->array[index] = data;
}