13.5 动态内存管理类

13.39 编写你自己版本的StrVec,包括自己版本的reserve、capacity和resize。

13.40 为你的StrVec类添加一个构造函数,它接收一个initializer_list<string>参数。

#include<memory>
#include<string>
#include<initializer_list>
class StrVec
{
public:
        //......
	StrVec(std::initializer_list<std::string> sl);//参数可变的构造函数
	void reserve(const size_t n);
	void resize(const size_t n, const std::string &str= "");
	//......
};
#include "StrVec.h"
#include<algorithm>
using namespace std;

allocator<string> StrVec::alloc;

StrVec::StrVec(initializer_list<string> sl) {
	auto newdata = alloc_n_copy(sl.begin(), sl.end());
	element = newdata.first;
	cap = first_free = newdata.second;
}

void StrVec::reserve(const size_t n) {
	if (n <= capacity()) return;
	if (size() == 0) {
		first_free = element = alloc.allocate(n);
		cap = element + n;
	}
	else {//每次都成两倍增长
		while (n > capacity())
			reallocate();
	}
}

void StrVec::resize(const size_t n, const string &str) {
	if (n < size()) {
		for (auto deldata = element + n; deldata != first_free; ++deldata)
			alloc.destroy(deldata);
	}
	else if (n < capacity()) {
		uninitialized_fill(first_free, element + n, str);
		first_free = element + n;
	}
	else {//每次都成两倍增长
		while (n > capacity())
			reallocate();
		uninitialized_fill(first_free, element + n, str);
		first_free = element + n;
	}
}
其余代码参考书本上的例子。

13.43 从写free成员,用for_each和lambda来代替for循环destroy元素。你更倾向于哪种实现,为什么?

void StrVec::free() {
	if (!element) return;
	for_each(element, first_free, [](string &str) {alloc.destroy(&str); });//for_each传递给lambda的实参是指针的解引用
	alloc.deallocate(element, cap - element);
}
觉得还是用for循环更好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值