C++ Primer(第五版) 13.5节练习

本文详细解答了C++ Primer第五版第13.5节的若干练习,包括StrVec类的设计、TextQuery类与QueryResult类的改进,以及使用lambda表达式优化内存管理。此外,还介绍了自定义String类及其测试代码。
摘要由CSDN通过智能技术生成

13.39    StrVec.h:

#ifndef	STRVEC_H
#define	STRVEC_H
#include <string>
#include <memory>

using namespace std;

class StrVec {
public:
	StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) { }
	StrVec(const StrVec&);
	StrVec(const std::string*, const std::string*);
	StrVec(initializer_list<string> lst);
	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 n) { if (n > capacity()) resize(n); }
	void resize(size_t);
	string& operator[](size_t n) { return elements[n]; }
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;	
};

#endif

StrVec.cc:

#include "StrVec.h"

#include <utility>
#include <iterator>

using namespace std;

allocator<string> StrVec::alloc; 

void StrVec::push_back(const string &s)
{
	chk_n_alloc();
	alloc.construct(first_free++, s);
}

pair<string*, string*>
StrVec::alloc_n_copy(const string *b, const string *e)
{
	string *data = alloc.allocate(e - b);
	return make_pair(data, uninitialized_copy(b, e, data));
}

void StrVec::free()
{
	if (elements) {
		for (auto p = first_free; p != elements; )
			alloc.destroy(--p);
		alloc.deallocate(elements, cap - elements);
	}
}

StrVec::StrVec(const StrVec &s)
{
	auto newdata = alloc_n_copy(s.begin(),
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值