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;
}
相关推荐
琳少_10 分钟前
java课堂笔记
java·开发语言·数据库·笔记
Brain 博览记2 小时前
脑机接口研究丨FPGA 5 毫秒完成运动想象分类
开发语言·论文阅读·人工智能·机器学习·fpga开发·分类·数据挖掘
Brain 博览记3 小时前
脑网络AI丨给图神经网络装上“信息高速路”
开发语言·网络·论文阅读·人工智能·深度学习·神经网络·机器学习
鱼很腾apoc3 小时前
【Redis】第2期 详解Redis五大数据结构:命令+C++实现、渐进式遍历与数据库管理
linux·服务器·c语言·数据结构·c++·redis·学习
郝学胜-神的一滴3 小时前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
bkspiderx14 小时前
C++符号冲突与内部符号优先策略详解
linux·服务器·c++·符号冲突·内部符号
两点王爷16 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
ShineWinsu16 小时前
对于Qt:条件变量(QWaitCondition)的解析
c++·qt·面试·线程·条件变量·客户端·锁
微笑星河q17 小时前
C++高阶之【多态】
开发语言·c++