-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDarray.h
84 lines (54 loc) · 1.19 KB
/
Darray.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
// #ifndef Darray
// #define Darray
#include<iostream>
using namespace std;
template <typename T> // class template
class Darray
{
private:
T* data;
int sz = 0;
int cap = 0;
public:
Darray(int s = 0, T v = T())
{
cap = 2*s;
sz = s;
data = new T[cap];
for(int i = 0; i < s; ++i)
data[i] = v;
}
~Darray() { delete[] data; }
int size() { return sz; }
bool empty() { return sz == 0; }
int capacity() { return cap; }
T at(int i) { return data[i]; }
T& operator[](int index)
{
if(index > sz-1 || index < 0)
{
throw invalid_argument( "memory does not exist" );
}
else
return data[index];
}
void pop_back()
{
if(sz > 0)
--sz;
}
void push_back(T v)
{
if(sz == cap)
{
cap = cap == 0 ? 1 : cap * 2; ; // Make room for the new element, this make sthe amortized complexity O(1)
T* new_data = new T[cap];
for(int i = 0; i < sz; ++i)
new_data[i] = data[i];
delete[] data;
data = new_data;
}
// Now sz < cap always
data[sz++] = v;
}
};