-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_vector.cpp
More file actions
112 lines (86 loc) · 2.29 KB
/
my_vector.cpp
File metadata and controls
112 lines (86 loc) · 2.29 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
#include "my_vector.h"
#include <iostream>
my_vector::my_vector() : data(nullptr), _size(0), _capacity(0) {};
my_vector::my_vector(const int len, const int val) : _size(len), _capacity(len) {
data = new int[_capacity];
for(int i = 0; i < _capacity; ++i)
data[i] = val;
}
my_vector::~my_vector() {
delete[] data;
}
my_vector::my_vector(const my_vector& other) : _size(other._size), _capacity(other._capacity) {
data = new int[_capacity];
for(int i = 0; i < _size; ++i)
data[i] = other.data[i];
}
my_vector& my_vector::operator=(const my_vector &other) {
if(this != &other) {
delete[] data;
_size = other._size;
_capacity = other._capacity;
data = new int[_capacity];
for(int i = 0; i < _size; ++i)
data[i] = other.data[i];
}
return *this;
}
my_vector::my_vector(my_vector&& other) noexcept {
_capacity = other._capacity;
_size = other._size;
data = other.data;
other.data = nullptr;
other._capacity = other._size = 0;
}
my_vector& my_vector::operator=(my_vector&& other) noexcept {
if(this != &other) {
delete[] data;
_capacity = other._capacity;
_size = other._size;
data = other.data;
other.data = nullptr;
other._capacity = other._size = 0;
}
return *this;
}
const int& my_vector::operator[](const int idx) const {
return data[idx];
}
int& my_vector::operator[](const int idx) {
return data[idx];
}
std::ostream& operator<<(std::ostream& os, const my_vector& obj) {
os << "[ ";
for(int i = 0; i < obj._size; ++i) {
os << obj[i];
if(i == obj._size - 1) {
os << " ";
} else {
os << ", ";
}
}
os << "]";
return os;
}
int my_vector::capacity() const {
return _capacity;
}
int my_vector::size() const {
return _size;
}
bool my_vector::empty() const {
return _size == 0;
}
void my_vector::push_back(int x) {
if(_size == _capacity) resize(_capacity == 0 ? 1 : _capacity * 2);
data[_size] = x;
++_size;
}
void my_vector::resize(int new_capacity) {
int* new_data = new int[new_capacity];
for(int i = 0; i < _size; ++i)
new_data[i] = std::move(data[i]);
delete[] data;
data = new_data;
_capacity = new_capacity;
}