C++ //练习 14.23 为你的StrVec类定义一个initializer_list赋值运算符。

C++ Primer(第5版) 练习 14.23

练习 14.23 为你的StrVec类定义一个initializer_list赋值运算符。

环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp 复制代码
class StrVec{
    public:
    StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {}
    StrVec(const StrVec &);
    StrVec &operator= (const StrVec &);
    ~StrVec();
    void push_back(const string &);
    size_t size() const { return first_free - elements; } 
    size_t capacity() const { return cap - elements; }
    string *begin() const { return elements; }
    string *end() const { return first_free; }
    void reserve(size_t s);
    void resize(size_t s);

	StrVec& operator=(std::initializer_list<std::string> li);

    private:
    Static allocator<string> alloc;
    void chk_n_alloc(){ if (size() == capacity()) reallocate(); }
    pair<string*, string*>alloc_n_copy(const string*, const string*);
    void free();
    void reallocate();
    string *elements;
    string *first_free;
    string *cap;
};

StrVec& StrVec::operator=(std::initializer_list<std::string> li){
	std::pair<std::string*, std::string*> data = alloc_n_copy(li,begin(), li.end());
	elements = data.first;
	first_free = cap = data.second;
	return *this;
}
相关推荐
Wish3D10 分钟前
阿里云OSS 上传文件 Python版本
开发语言·python·阿里云
凤年徐10 分钟前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii13 分钟前
C++11 右值引用:从入门到精通
开发语言·c++
朝新_3 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir3 小时前
Calendar类日期设置进位问题
java·开发语言
木子.李3474 小时前
排序算法总结(C++)
c++·算法·排序算法
风逸hhh4 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮5 小时前
Python训练第四十三天
开发语言·python
闪电麦坤955 小时前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
freyazzr5 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++