-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmyvector.cpp
More file actions
38 lines (37 loc) · 901 Bytes
/
myvector.cpp
File metadata and controls
38 lines (37 loc) · 901 Bytes
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
#include "myvector.h"
MyVector::MyVector(int length_of_vector) {
init(length_of_vector);
}
void MyVector::init(int length_of_vector){
allocated_length = length = length_of_vector;
ptr = (twonum*)malloc(allocated_length*sizeof(twonum));
}
void MyVector::push_back(twonum part){
if (length == allocated_length){
ptr = (twonum*)realloc(ptr, 2*allocated_length*sizeof(twonum));
allocated_length *=2;
}
ptr[length] = part;
length+=1;
}
void MyVector::pop_back(){
length--;
if(4*length <= allocated_length){
ptr = (twonum*)realloc(ptr, allocated_length/2*sizeof(twonum));
}
}
void MyVector::shrink(int x){
if (x>=allocated_length) return;
if (4*x <= allocated_length){
ptr = (twonum*)realloc(ptr, x*sizeof(twonum));
allocated_length = x;
}
length = x;
}
MyVector::twonum& MyVector::operator[](int index) {
return ptr[index];
}
void MyVector::free_mem(){
free(ptr);
ptr = NULL;
}