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
|
//定义StrBlob类
class StrBlob{
public:
//定义类型
using size_type=vector<string>::size_type;
//两个构造函数,默认初始化和列表初始化
StrBlob();
StrBlob(initializer_list<string> il);
//以下是对底层vector操作的封装
size_type size() const {return data->size();}
bool empty() const {return data->empty();}
void push_back(const string &t) {data->push_back(t);}
void pop_back();
string &front();
string &back();
private:
//用shared_ptr管理底层的vector<string>数据
shared_ptr<vector<string>> data;
//检查索引i是否越界,越界时用msg抛出异常
void check(size_type i, const string &msg) const;
};
//默认构造函数,底层vector<string>默认初始化,返回shared_ptr用于初始化data
StrBlob::StrBlob():
data(make_shared<vector<string>>())
{}
//构造函数,底层vector<string>列表初始化,返回shared_ptr用于初始化data
StrBlob::StrBlob(initializer_list<string> il):
data(make_shared<vector<string>>(il))
{}
//检查下标是否越界
void StrBlob::check(size_type i, const string &msg) const {
if(i>=data->size())
throw out_of_range(msg);
}
//以下3个函数分别实现front、back、pop_back操作,用0来check索引判断是否为空
string &StrBlob::front(){
check(0,"front on empty StrBlob");
return data->front();
}
string &StrBlob::back(){
check(0,"back on empty StrBlob");
return data->back();
}
void StrBlob::pop_back(){
check(0,"pop_back on empty StrBlob");
data->pop_back();
}
/* 使用StrBlob */
StrBlob b1; //创建新StrBlob
|