自己实现一个vector类

准备面试,看到很多人说遇到面试官让自己在纸上写一个std类,所以我就拿std::vector作为练手。

主要思想就是使用swap保证异常安全性,遵守Effective C++的一些item,比如从copy-constructorassign-constructor提取共同的代码组成init函数。

虽然代码比较简单,但还是出现了越界等问题调试了很久,可能手太生了,以后得多练练!

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
127
128
129
130
131
#include <utility>
#include <algorithm>
#include <iostream>
class myvec {
private:
int *mdata = nullptr;
int msize = 11;
int mlastidx = -1;
void ensureSize() {
if (msize <= mlastidx + 1) {
reserve(msize * 2);
}
}
void init(const myvec &vec) {
if (&vec == this)
return;
myvec newvec(vec.msize);
for (int i = 0; i <= vec.mlastidx; ++i) {
newvec.insert(vec.mdata[i]);
}
swap(newvec);
}
public:
myvec() : myvec(11) {
}
myvec(int capacity) : msize(capacity) {
try {
mdata = new int[capacity];
}
catch (const std::bad_alloc &e) {
std::cerr << e.what() << std::endl;
abort();
}
}
myvec(const myvec &vec) {
init(vec);
}
~myvec() {
delete[] mdata;
std::cout<<"deconstructed"<<std::endl;
}
const myvec &operator=(const myvec &vec) {
init(vec);
return *this;
}
int size() {
return mlastidx + 1;
}
int &operator[](int index) {
if (index < 0 || index > mlastidx)
throw "invalid access";
return mdata[index];
}
void swap(myvec &other) {
std::swap(this->msize, other.msize);
std::swap(this->mdata, other.mdata);
std::swap(this->mlastidx, other.mlastidx);
}
void reserve(int capacity) {
if (capacity <= mlastidx) {
return;
}
myvec newvec(capacity);
for (int i = 0; i <= mlastidx; ++i) {
newvec.insert(mdata[i]);
}
swap(newvec);
}
bool empty() {
return mlastidx == -1;
}
void insert(int val) {
ensureSize();
mlastidx++;
mdata[mlastidx] = val;
}
void erase(int index) {
if (index < 0 || index > mlastidx) {
return;
}
for (int i = index; i < mlastidx; ++i) {
mdata[i] = mdata[i + 1];
}
mlastidx--;
}
int find(int val) {
for (int i = 0; i <= mlastidx; ++i) {
if (mdata[i] == val) {
return i;
}
}
}
int count(int val) {
int cnt = 0;
for (int i = 0; i <= mlastidx; ++i) {
if (mdata[i] == val) {
cnt++;
}
}
return cnt;
}
void clear() {
myvec newvec(msize);
swap(newvec);
}
};