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;
}
相关推荐
apcipot_rain5 小时前
C++转Java日记(04)
java·开发语言·c++
NEFU_Jyj5 小时前
牛客周赛R168
算法
云和数据.ChenGuang6 小时前
LangGraph 异步 Node 的设计与写法实践
开发语言·人工智能·python·机器学习·php
WL学习笔记7 小时前
vector模拟实现
c++
蜗牛一步步往上爬9 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
张张123y11 小时前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
Navigator_Z13 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack13 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH14 小时前
C++ 标准库算法全景指南
数据结构·c++·算法