-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector.cpp
More file actions
104 lines (64 loc) · 1.51 KB
/
Vector.cpp
File metadata and controls
104 lines (64 loc) · 1.51 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
Returns a reference to the element at position index~/**
* @file Vector.cpp
* @author Lizette Navarrete
* @date 2025-02-08
* @brief Implementation file for Vector Class
*
* Implements the Vector class similar to the vector library
*/
#include "Vector.h"
using namespace std;
Vector::Vector(){
vec_capacity = 0;
vec_size = 0;
vec_ptr = nullptr;
}
Vector::Vector(const Vector &other){
vec_capacity = other.vec_capacity;
vec_size = other.vec_size;
vec_ptr = new int[vec_capacity];
for(int i = 0; i < vec_size; i++){
vec_ptr[i] = other.vec_ptr[i];
}
delete[] other.vec_ptr;
}
Vector::~Vector(){
delete[] vec_ptr;
}
Vector& Vector::operator=(const Vector &other){
// this and other
delete[] vec_ptr;
vec_size = other.vec_size;
vec_capacity = other.vec_capacity;
vec_ptr = new int[vec_capacity];
for(int i = 0; i <vec_size; i++){
vec_ptr[i] = other.vec_ptr[i];
}
return *this;
}
int Vector::size(){
return vec_size;
}
int Vector::capacity(){
return vec_capacity;
}
void Vector::push_back(int element){
if(vec_size >= vec_capacity)
reserve(max(2 * vec_capacity, 1));
vec_ptr[vec_size] = element;
vec_size++;
}
void Vector::reserve(int n){
if(n >= vec_capacity){
int* temp_ptr = new int[n];
for(int i = 0; i < vec_size; i++){
temp_ptr[i] = vec_ptr[i];
}
delete[] vec_ptr;
vec_ptr = temp_ptr;
vec_capacity = n;
}
}
int& Vector::operator[](unsigned int index){
return vec_ptr[index];
}