练习 13.39:编写你自己版本的StrVec,包括自己版本的reserve,capacity和resize。
allocate_and_construct(std::size_t):
void StrVec::allocate_and_construct(std::size_t newcapacity) {
auto newdata = alloc.allocate(newcapacity);
auto dest = newdata;
auto elem = elements;
for (std::size_t i = 0; i != size(); ++i) {
alloc.construct(dest++, std::move(*elem++));
}
free();
elements = newdata;
first_free = dest;
cap = elements + newcapacity;
}
construct_each(std::string *&, std::string *, const std::string &);
void StrVec::construct_each(std::string *&begin, std::string *end, const std::string &newVal) {
uninitialized_fill(begin, end, newVal);
begin = end;
}
reserve():
void StrVec::reserve(std::size_t n) {
if (n > capacity()) {
allocate_and_construct(n);
}//如果需求大小小于或等于当前容量,reserve什么也不做。
}
resize(std::size_t, const std::string &s):
void StrVec::resize(size_t n, const std::string &s) {
if (n < size()) {
while (first_free != elements + n) {
alloc.destroy(--first_free);
}
} else if (n > capacity()) {
allocate_and_construct((3 * n + 1) / 2);
construct_each(first_free, elements + n, s);
} else if (n > size()) {
construct_each(first_free, elements + n, s);
}
}
resize(std::size_t):
void StrVec::resize(size_t n) {
resize(n, std::string());
}