-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_vector.cpp
More file actions
127 lines (123 loc) · 2.18 KB
/
my_vector.cpp
File metadata and controls
127 lines (123 loc) · 2.18 KB
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
#include <iostream>
#include "my_vector.h"
void ivector::copy(int *ptr = nullptr)
{
if (ptr == nullptr)
{
ptr = new int[m_capacity];
for(int i=0; i<m_size; ++i)
{
ptr[i] = m_buffer[i];
}
delete [] m_buffer;
m_buffer = ptr;
}
else
{
m_buffer = new int[m_capacity];
for(int i=0; i<m_size; ++i)
{
m_buffer[i] = ptr[i];
}
}
}
ivector::ivector()
{
m_size = 0;
m_capacity = 1;
m_buffer = new int[m_capacity];
}
ivector::~ivector()
{
delete[] m_buffer;
}
ivector::ivector(const ivector &ive)
{
m_size = ive.m_size;
m_capacity = ive.m_capacity;
m_buffer = new int[m_capacity];
copy(ive.m_buffer);
}
ivector& ivector::operator= (const ivector& ive)
{
if(this == &ive)
{
return *this;
}
m_size = ive.m_size;
m_capacity = ive.m_capacity;
copy(ive.m_buffer);
return *this;
}
bool ivector::empty()
{
return !(m_size);
}
int ivector::size()
{
return m_size;
}
void ivector::push_back(int element)
{
if(m_size == m_capacity)
{
m_capacity *= 2;
copy();
}
m_buffer[m_size] = element;
++m_size;
}
int ivector::pop_back()
{
if(m_size <= m_capacity/2)
{
m_capacity = m_capacity/2 + m_capacity%2;
copy();
}
--m_size;
return m_buffer[m_size];
}
void ivector::push_front(int element)
{
if(m_size == m_capacity)
{
m_capacity *=2 ;
int* ptr = new int[m_capacity];
ptr[0] = element;
for (int i=1; i<= m_size; ++i)
{
ptr[i] = m_buffer[i-1];
}
delete [] m_buffer;
m_buffer = ptr;
}
for(int i=m_size-1; i>0; --i)
{
m_buffer[i+1]=m_buffer[i];
}
m_buffer[0]=element;
}
int ivector::pop_front()
{
if(this->empty())
{
return -1;
}
int tmp = m_buffer[0];
for(int i=0; i<m_size; ++i)
{
m_buffer[i] = m_buffer[i+1];
}
if(m_size <= m_capacity/2)
{
m_capacity = m_capacity/2 + m_capacity%2;
copy();
}
--m_size;
return tmp;
}
void ivector::reserve(int count)
{
m_capacity = count;
copy();
}