-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmvector.h
126 lines (110 loc) · 2.91 KB
/
mvector.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
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
#ifndef MVector_h
#define MVector_h
#include <initializer_list>
#include <vector>
template <class T>
class mvector{
public:
using value_type = T;
mvector(){}
mvector(const mvector & mvect){
for (const T & val : mvect)
push_back(val);
}
mvector(const std::vector<T> & mvect){
for (const T & val : mvect)
push_back(val);
}
mvector(int n){
resize(n);
}
mvector(std::initializer_list<T> list){
for (auto & val : list)
push_back(val);
}
~mvector(){
clear();
}
int size() const{
return m_size;
}
void push_back(const T & a){
T b = a;
reserve(m_size+1);
m_mem[m_size++] = std::move(b);
}
void pop_back(){
m_mem[--m_size] = T();
}
const T & operator [] (int i) const{
return m_mem[i];
}
T & operator [] (int i){
return m_mem[i];
}
mvector & operator = (const std::initializer_list<T> & list){
clear();
for (auto & val : list)
push_back(val);
return *this;
}
mvector & operator = (const std::vector<T> & mvect){
clear();
for (const T & val : mvect)
push_back(val);
return *this;
}
mvector & operator = (const mvector & mvect){
clear();
for (int i = 0; i < mvect.size(); ++i)
push_back(mvect[i]);
return *this;
}
void resize(int size){
while (size < m_size)
pop_back();
while (size > m_size)
push_back(T());
}
void reserve(int size){
if (size > m_cap){
int cap = (m_cap == 0 ? 1 : m_cap);
while (cap < size)
cap *= 2;
T * mem = new T[cap]();
for (int i = 0; i < m_size; ++i)
mem[i] = std::move(m_mem[i]);
delete[] m_mem;
m_mem = mem;
m_cap = cap;
}
}
void swap(mvector& m){
std::swap(m_mem, m.m_mem);
std::swap(m_cap, m.m_cap);
std::swap(m_size, m.m_size);
}
void clear(){
delete[] m_mem;
m_mem = nullptr;
m_size = 0;
m_cap = 0;
}
T * begin(){
return m_mem;
}
const T * begin() const {
return m_mem;
}
T * end(){
return m_mem + m_size;
}
const T * end() const {
return m_mem + m_size;
}
private:
T * m_mem = nullptr;
int m_size = 0;
int m_cap = 0;
};
#endif