卡在第 11 章练习 11-6 的擦除功能中。我已经销毁了这些对象,但我不知道如何使用分配器库中的释放来返回空间。
请保释我。PS:这不是作业,但我正在家里练习
下面是来自 Accelerated C++ 的代码,然后是我修改后的擦除函数。谢谢`
template <class T> class Vec
{
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef size_t size_type;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
Vec() { create(); }
explicit Vec(size_type n, const T& t = T()) { create(n, t); }
Vec(const Vec& v) { create(v.begin(), v.end()); }
Vec& operator=(const Vec&);
~Vec() { uncreate(); }
T& operator[](size_type i) { return data[i]; }
const T& operator[](size_type i ) const { return data[i]; }
void push_back(const T& t)
{
if (avail == limit)
{
grow();
}
unchecked_append(t);
}
iterator erase(iterator);
iterator erase( iterator, iterator );
void clear();
size_type size() const { return avail - data; }
iterator begin() { return data; }
const iterator begin() const { return data; }
iterator end() { return avail; }
const iterator end() const { return avail; }
private:
iterator data;
iterator avail;
iterator limit;
std::allocator<T> alloc;
void create();
void create(size_type, const T&);
void create(const_iterator, const_iterator);
void uncreate();
void grow();
void unchecked_append(const T&);
};
我的代码
template <class T> typename Vec<T>::iterator Vec<T>::erase(iterator first, iterator second )
{
if( second < first )
{
throw std::out_of_range("Iterator out of bounds.");
}
if( first < data || second >= avail )
{
throw std::out_of_range("Iterator out of bounds.");
}
iterator last = avail -1 ;
iterator i = first ;
iterator j = second ;
while( j <= last )
{
*i++ = *j++ ;
}
// destroy each initilsed space
iterator new_avail = avail - first + second ;
std::cout << " end " << end() << std::endl;
while( avail != new_avail )
{
alloc.destroy(--avail ) ;
}
// dellocate space how to do that ?
alloc.deallocate( avail -1, ); // not sure what to do here
return first ;
}