13.39 编写你自己版本的StrVec,包括自己版本的reserve、capacity和resize。
13.40 为你的StrVec类添加一个构造函数,它接收一个initializer_list参数。
#include
#include
#include
class StrVec
{
public:
//......
StrVec(std::initializer_list sl);//参数可变的构造函数
void reserve(const size_t n);
void resize(const size_t n, const std::string &str= "");
//......
};
#include "StrVec.h"
#include
using namespace std;
allocator StrVec::alloc;
StrVec::StrVec(initializer_list 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循环更好。