-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.cpp
More file actions
103 lines (90 loc) · 2.17 KB
/
Copy pathvector.cpp
File metadata and controls
103 lines (90 loc) · 2.17 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
#include "vector.h"
#include <algorithm>
#include <stdexcept>
template<class T, class A>
vector<T, A>::vector(const vector& arg)
:sz{arg.sz}, elem(new T[arg.sz])
{
std::copy(arg.elem, arg.elem + arg.sz, elem);
}
template<class T, class A>
vector<T, A>::vector(vector&& a)
:sz{a.sz}, elem{a.elem}
{
a.sz = 0;
a.elem = nullptr;
}
template<class T, class A>
vector<T, A>& vector<T, A>::operator=(vector&& a)
{
delete[] elem;
elem = a.elem;
sz = a.sz;
a.elem = nullptr;
a.sz = 0;
return *this;
}
template<class T, class A>
void vector<T, A>::reserve(int newalloc)
{
if (newalloc <= this->space) return;
vector_base<T, A> b(this->alloc, newalloc);
std::uninitialized_copy(b.elem, &b.elem[this->sz], this->elem);
T* p = alloc.allocate(newalloc);
for (int i = 0; i < this->sz; ++i)
alloc.destroy(&this->elem[i]);
std::swap<vector_base<T, A>>(*this, b);
}
template<class T, class A>
int vector<T, A>::capacity() const { return space; }
template<class T, class A>
void vector<T, A>::resize(int newsize, T val)
{
reserve(newsize);
for (int i = sz; i < newsize; ++i)
alloc.construct(&elem[i], val);
for (int i = newsize; i < sz; ++i)
alloc.destroy(&elem[i]);
sz = newsize;
}
template<class T, class A>
void vector<T, A>::push_back(const T& val)
{
if (space == 0)
reserve(8);
else if (sz == space)
reserve(2 * space);
alloc.construct(&elem[sz], val);
++sz;
}
template<class T, class A>
vector<T, A>& vector<T, A>::operator=(const vector& a)
{
if (this == &a) return *this;
if (a.sz <= space)
{
for (int i = 0; i < a.sz; ++i)
elem[i] = a.elem[i];
sz = a.sz;
return *this;
}
T* p = new T[a.sz];
for (int i = 0; i < a.sz; ++i)
p[i] = a.elem[i];
delete[] elem;
space = sz = a.sz;
elem = p;
return *this;
}
template<class T, class A>
T& vector<T, A>::at(int n)
{
if (n < 0 || sz <= n) throw std::out_of_range();
return elem[n];
}
template<class T, class A>
const T& vector<T, A>::at(int n) const
{
if (n < 0 || sz <= n) throw std::out_of_range();
return elem[n];
}