forked from demon90s/CppStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_13_26.cpp
101 lines (78 loc) · 2.18 KB
/
exercise_13_26.cpp
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
// 练习13.26:对上一题中描述的StrBlob类,编写你自己的版本。
#include <iostream>
#include <vector>
#include <string>
#include <initializer_list>
#include <memory>
class StrBlob {
public:
typedef std::vector<std::string>::size_type size_type;
StrBlob() : data(std::make_shared<std::vector<std::string>>()) {}
StrBlob(std::initializer_list<std::string> il) :
data(std::make_shared<std::vector<std::string>>(il)) {}
StrBlob(const StrBlob &sb) : data(std::make_shared<std::vector<std::string>>(*sb.data)) {}
StrBlob& operator=(const StrBlob &sb)
{
data = std::make_shared<std::vector<std::string>>(*sb.data);
return *this;
}
inline size_type size() const { return data->size(); }
inline bool empty() const { return data->empty(); }
// 添加和删除元素
inline void push_back(const std::string &t) { data->push_back(t); }
inline void pop_back();
// 元素访问
inline std::string& front();
inline std::string& back();
inline std::string& front() const;
inline std::string& back() const;
std::string& operator[](size_type i) { return (*data)[i]; } // 省略了check
private:
std::shared_ptr<std::vector<std::string>> data;
// 如果data[i]不合法,抛出一个异常
inline void check(size_type i, const std::string &msg) const;
};
void StrBlob::check(size_type i, const std::string &msg) const
{
if (i >= data->size())
throw std::out_of_range(msg);
}
std::string& StrBlob::front()
{
// 如果vector为空,check会抛出一个异常
check(0, "front on empty StrBlob");
return data->front();
}
std::string& StrBlob::back()
{
check(0, "back on empty StrBlob");
return data->back();
}
void StrBlob::pop_back()
{
check(0, "pop_back on empty StrBlob");
return data->pop_back();
}
std::string& StrBlob::front() const
{
check(0, "front on empty StrBlob");
return data->front();
}
std::string& StrBlob::back() const
{
check(0, "back on empty StrBlob");
return data->back();
}
int main()
{
using namespace std;
StrBlob sb1;
sb1.push_back("hi");
cout << "sb1[0]: " << sb1[0] << endl;
StrBlob sb2 = sb1;
cout << "sb2[0]: " << sb2[0] << endl;
sb2[0] = "wow";
cout << "sb1[0]: " << sb1[0] << endl;
cout << "sb2[0]: " << sb2[0] << endl;
return 0;
}