C++ Primer 第五版 中文版 练习 13.26
题目: 对上一题中描述的StrBlob类,编写你自己的版本。
StrBlob.h
- #pragma once
- #include <memory>
- #include <vector>
- #include <string>
- #include "StrBlobPtr.h"
- class StrBlob
- {
- public:
- friend class StrBlobPtr;
- typedef std::vector<std::string>::size_type size_type;
- // 下面这个等同于上面这个。
- // using size_type = std::vector<std::string>::size_type;
- StrBlob();
- StrBlob(std::initializer_list<std::string> il);
- //拷贝构造函数
- StrBlob(const StrBlob&);
- //拷贝赋值运算符
- StrBlob& operator=(const StrBlob&);
- size_type size() const { return data->size(); }
- bool empty() const { return data->empty(); }
- //添加和删除元素
- void push_back(const std::string &t) { data->push_back(t); }
- void pop_back();
- //元素访问
- std::string& front();
- std::string& back();
- StrBlobPtr begin() { return StrBlobPtr(*this); }
- StrBlobPtr end()
- {
- auto ret = StrBlobPtr(*this, data->size());
- return ret;
- }
- private:
- std::shared_ptr<std::vector<std::string>> data;
- //如果data[i]不合法,抛出一个异常。
- void check(size_type i, const std::string &msg) const;
- };
- #include "StrBlob.h"
- using namespace std;
- //定义构造函数
- StrBlob::StrBlob() :data(make_shared<vector<string>>())
- {
- }
- StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il))
- {
- }
- //定义拷贝构造函数
- StrBlob::StrBlob(const StrBlob &SB) :data(make_shared<vector<string>>(SB.data))
- {
- }
- //定义拷贝赋值运算符
- StrBlob& StrBlob::operator=(const StrBlob &SB)
- {
- auto newdata = shared_ptr<vector<string>>(SB.data);
- data = newdata;
- return *this;
- }
- void StrBlob::check(size_type i, const string &msg) const
- {
- if (i >= data->size())
- throw out_of_range(msg);
- }
- 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();
- }