C++primer 12.1.1节练习

练习12.1

b1和b2共享一个strBlob对象,所以他们都有4个元素;

练习12.2

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <set>
 6 #include <map>
 7 #include <algorithm>
 8 #include <vector>
 9 #include <algorithm>
10 #include <iterator>
11 #include <unordered_map>
12 #include <memory>
13 
14 using namespace std;
15 
16 class strBlob {
17     friend void print(strBlob s);
18 public:
19     typedef vector<string>::size_type size_type;
20     strBlob();
21     strBlob(initializer_list<string> il);
22     size_type size() const { return data->size(); }
23     bool empty() const { return data->empty(); }
24     void push_back(const string &t);
25     void pop_back();
26     const string &front();
27     const string &back();
28 private:
29     shared_ptr<vector<string>> data;
30     void check(size_type i, const string &msg) const;
31 };
32 
33 void print(strBlob s);
34 
35 int main()
36 {
37     strBlob p1({ "asd", "qew", "jkl" });
38     print(p1);
39     p1.push_back("dqw");
40     print(p1);
41     p1.pop_back();
42     p1.pop_back();
43     print(p1);
44     cout << endl;
45     cout << p1.front() << endl;
46     cout << p1.back() << endl;
47     system("pause");
48     return 0;
49 }
50 
51 strBlob::strBlob() : data(make_shared<vector<string>>()) {}
52 strBlob::strBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}
53 void strBlob::push_back(const string & t)
54 {
55     data->push_back(t);
56 }
57 void strBlob::pop_back()
58 {
59     check(0, "pop_back on empty StrBlob");
60     data->pop_back();
61 }
62 const string & strBlob::front()
63 {
64     check(0, "front on empty StrBlob");
65     return data->front();
66     // TODO: 在此处插入 return 语句
67 }
68 const string & strBlob::back()
69 {
70     check(0, "back on empty StrBlob");
71     return data->back();
72     // TODO: 在此处插入 return 语句
73 }
74 
75 
76 void strBlob::check(size_type i, const string & msg) const
77 {
78     if (i >= data->size())
79         throw out_of_range(msg);
80 }
81 
82 void print(strBlob s)
83 {
84     for (auto c : *(s.data))
85         cout << c << endl;
86     cout << endl;
87 }

练习12.3

push_back和pop_back的语义分别是向StrBlob对象共享的vector对象添加和从其删除元素。因此,我们不应该为其重载const版本,因为常量StrBlob对象是不应该被允许修改共享vector对象的内容的。 

练习12.4

size_type由string类类型和vector类类型定义的类型,用以保存任意string对象或vector对象的长度,标准库类型size_type定义为unsigned类型

练习12.5

explicit关键字是使构造函数必须显式构造,这样的好处在于程序会更加明了,而且排除了一些由于隐式转换造成的实参类型错误等问题,缺点在于程序灵活性会大大降低。

posted @ 2017-08-28 16:52  五月份小姐  阅读(551)  评论(0编辑  收藏  举报