-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathvector.h
86 lines (71 loc) · 1.37 KB
/
vector.h
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
/*
TOPIC: 05 - Container Design
We will be designing our own vector class.
To understand, How STL containers are implemented ?
NOTE: filename: vector.h
*/
class Vector
{
int cs; // cs: current size
int ms; // cs: max size
int *arr; // pointer
public:
Vector() // constructor
{
cs = 0;
ms = 1;
arr = new int[ms];
}
void push_back(const int d) // d: data
{
if(cs == ms)
{
int *oldArr = arr;
arr = new int[2*ms];
ms = 2*ms;
for(int i=0; i<cs; i++)
{
arr[i] = oldArr[i];
}
// clear old memory
delete [] oldArr;
}
arr[cs] = d;
cs++;
}
void pop_back()
{
// we don't want to shrink the array. So, just decrement index
cs--;
}
int front() const
{
return arr[0];
}
int back() const
{
return arr[cs-1];
}
bool empty() const
{
return cs==0;
}
int capacity() const
{
return ms;
}
// gives the element at i-th index
int at(const int i)
{
return arr[i];
}
int size() const
{
return cs;
}
// operator overloading
int operator[](const int i)
{
return arr[i];
}
};