![]() |
#2
rjsp2017-04-10 16:00
|
代码如下

#ifndef STRVEC_H
#define STRVEC_H
#include<string>
#include<memory>
#include<utility>
using std::string;
class StrVec{
public:
StrVec() : top(nullptr), back(nullptr), last(nullptr) {};
StrVec(const StrVec&);
StrVec& operator=(const StrVec&);
~StrVec();
void push_back(string&);
void erase();
size_t size() const { return back - top; }
size_t capacity() const { return last - top; }
string* begin() const { return top; }
string* end() const { return last; }
private:
string *top;
string *back;
string *last;
void free();
void reallocate();
std::allocator<string> alloc;
std::pair<string*,string*> alloc_n_copy(string*,string*); //const??
void cheak_full()
{
if (capacity() == size()) reallocate();
}
};
void StrVec::push_back(string &a)
{
cheak_full();
alloc.construct(back++, a);
}
std::pair<string*, string*> StrVec::alloc_n_copy(string* begin, string* end)
{
auto data = alloc.allocate(end - begin);
return{ data, std::uninitialized_copy(begin, end, data) };
}
StrVec::StrVec(const StrVec& A)
{
auto data = alloc_n_copy(A.begin(), A.end());
top = data.first;
back = last = data.second;
}
StrVec& StrVec::operator=(const StrVec& A)
{
auto data = alloc_n_copy(A.begin(), A.end());
free();
top = data.first;
back = last = data.second;
return *this;
}
StrVec::~StrVec()
{
free();
}
void StrVec::reallocate()
{
auto newspace = size() ? size() * 2 : 1;
auto view = alloc.allocate(newspace);
auto newtop = view;
for (auto a = top; a != back; a++)
{
alloc.construct(view++, std::move(*a));
}
free();
top = newtop;
back = view;
last = top + newspace;
}
void StrVec::free()
{
if (top)
{
for (auto a = top; a != back; a++)
{
alloc.destroy(a);
}
alloc.deallocate(top, capacity());
}
}
#endif
报错是
只有本站会员才能查看附件,请 登录
感觉是
只有本站会员才能查看附件,请 登录
这段代码的错。但是感觉写的和书上差不多,并没有什么毛病。。求教到底哪里有错