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;
}
相关推荐
快乐非自愿几秒前
Lfu缓存在Rust中的实现及源码解析
开发语言·缓存·rust
小字节,大梦想2 分钟前
C语言_结构体初阶(还未写完)
c语言·开发语言
黑泽明Coding4 分钟前
编译rust程序,并让它依赖低版本的GLIBC库
开发语言·rust
人才程序员4 分钟前
【Rust入门】生成随机数
开发语言·数据库·后端·单片机·rust
Roy Teng4 分钟前
数学建模MATLAB绘图大全
开发语言·数学建模·matlab
tRNA做科研10 分钟前
【基于R语言群体遗传学】-3-计算等位基因频率
开发语言·r语言
敲代码的小白帆37 分钟前
学java的第3天 后端商城小程序工作
java·开发语言·小程序
wfsm43 分钟前
spring04事务
java·开发语言
满心欢喜love1 小时前
Python爬虫康复训练——笔趣阁《神魂至尊》
开发语言·爬虫·python
卡戎-caryon1 小时前
【数据结构】06.栈&&队列
c语言·数据结构·算法·链表