注册 登录
编程论坛 C++教室

按照c++primer 上的代码做了个string的类。类似vector结果编译出错

qq826647235 发布于 2017-04-10 14:54, 1627 次点击
按照c++primer 上的代码做了个string的类。类似vector结果编译出错

代码如下
程序代码:

#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


报错是
只有本站会员才能查看附件,请 登录


感觉是
只有本站会员才能查看附件,请 登录

这段代码的错。但是感觉写的和书上差不多,并没有什么毛病。。求教到底哪里有错
1 回复
#2
rjsp2017-04-10 16:00
代码的语法没问题
……<因为你贴的是图片,我没法拷贝,也没闲工夫照着图片重新一个字一个字的敲键盘>……”这句话说的是“unsafe”,而“unsafe”只是M$一家之言,是个瞎扯蛋的屁话。
要么你换用标准的C++编译器,要么按照M$的提示加上“……<因为你贴的是图片,我没法拷贝,也没闲工夫照着图片重新一个字一个字的敲键盘>……
1