1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
|
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class My_allocator
{
public:
T* allocate(int n); // allocate space for n objects of type T
void deallocate(T* p, int n); // deallocate n objects of type T starting at p
void construct(T* p, const T& v); // construct a T with the value v in p
void destroy(T* p); // destroy the T in p
};
//-------------------------------------------------
template<class T>
T* My_allocator<T>::allocate(int n)
{
return nullptr;
}
//------------------------------
template<class T>
void My_allocator<T>::deallocate(T * p, int n)
{
}
//------------------------------
template<class T>
void My_allocator<T>::construct(T * p, const T & v)
{
}
//------------------------------
template<class T>
void My_allocator<T>::destroy(T * p)
{
}
//------------------------------------------------
template <class T, class A = My_allocator<T> >
class Vector : public vector<T>
{
A alloc;
int sz;
T* elem;
int space;
public:
Vector() : vector<T>() {}
Vector(int n) :vector<T>(n) {}
Vector(int n, const T& v) :vector<T>(n, v) {}
~Vector() { delete[] elem; }
T& operator[](unsigned int n) // rather than return at(i);
{
if (i < 0 || this->size() <= i)
throw Range_error(i);
return vector<T>::operator[](i);
}
const T& operator[](unsigned int n) const
{
if (i < 0 || this->size() <= i)
throw Range_error(i);
return vector<T>::operator[](i);
}
void reverse(int);
void push_back(const T&);
void resize(int, T val = T());
int size() const { return sz; }
int capacity() const { return space; }
};
//------------------------------------------------
template <class T, class A>
void Vector<T, A>::reverse(int newalloc)
{
if (newalloc <= space)
return;
T* p = alloc.allocate(newalloc);
for (int i = 0; i < sz; ++i)
alloc.construct(&p[i], elem[i]);
for (int i = 0; i < sz; ++i)
alloc.destroy(&elem[i]);
alloc.deallocate(elem, space);
elem = p;
space = newalloc;
}
//-------------------------------------------
template <class T, class A>
void Vector<T, A>::push_back(const T& val)
{
if (space == 0)
reverse(8);
else if (sz == space)
reverse(2 * space);
alloc.construct(&elem[sz], val);
++sz;
}
//-------------------------------------
template <class T, class A>
void Vector<T, A>::resize(int newsize, T val = T())
{
reserve(newsize);
for (int i = sz; i < newsize; ++i)
alloc.construct(&elem[i], val); // construct
for (int i = newsize; i < sz; ++i)
alloc.destroy(&elem[i]); // destroy
sz = newsize;
}
//--------------------------------
int main()
{
return 0;
}
|