卡在11練習11-6的擦除功能。我已經銷燬了這些對象,但我不知道如何使用allocator庫中的釋放來返回空間。加速C++練習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 ;
}
什麼是你真正想幹什麼? – thecoshman