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
|
#ifndef VECTOR_HPP
#define VECTOR_HPP
//#include "test.hpp"
#include <vector>
#include <algorithm>
#include <memory>
template<class Out, class T>
void uninitialized_fill(Out, const T&);
template<class In, class Out>
Out uninitialized_copy(In, In, Out);
template<typename T>
class Vector
{
using iterator = T*;
using const_iterator = const T*;
using size_type = size_t;
using value_type = T;
private:
iterator data;
iterator limit;
iterator avail;
public:
Vector();
explicit Vector(size_type n, const T &val = T())
{ create(n, val); }
Vector(const Vector &v)
{create(v.begin(), v.end());}
Vector &operator=(const Vector& rhs);
~Vector()
{ uncreate(); }
T &operator[](size_type i)
{ return data[i]; }
const T& operator[](size_type i)const
{ return data[i]; }
iterator begin()
{return data;}
const_iterator begin() const
{return data;}
iterator end()
{return limit;}
const_iterator end() const
{return limit;}
void push_back(const T&);
size_type size() const
{return avail - data;}
std::allocator<T> alloc;
void create()
{data = avail = limit = 0;}
void create(size_type, const T&);
void create(const_iterator, const_iterator);
void uncreate();
void grow();
void unchecked_append(const T& val)
{alloc.construct(avail++, val);}
};
template <class T>
void Vector<T>::push_back(const T& val)
{
if(avail == limit)
grow();
unchecked_append(val);
}
template <class T>
Vector<T>::Vector()
{
create();
}
template <class T>
void Vector<T>::create(size_type n, const T& val)
{
data = alloc.allocate(n);
limit = avail = data + n;
unitialized_fill(data, limit, val);
}
template <class T>
void Vector<T>::create(const_iterator i, const_iterator j)
{
data = alloc.allocate(j - i);
limit = avail = unitialized_copy(i, j, data);
}
template <class T>
void Vector<T>::uncreate()
{
if(data)
{
iterator it = avail;
while(it != data)
{
alloc.destroy(--it);
}
alloc.deallocate(data, limit - data);
}
data = limit = avail = 0;
}
template <class T>
void Vector<T>::grow()
{
size_type new_size = std::max(2 * (limit - data), ptrdiff_t(1));
iterator new_data = alloc.allocate(new_size);
iterator new_avail = uninitialized_copy(data, avail, new_data);
uncreate();
data = new_data;
avail = new_avail;
limit = data + new_size;
}
#endif
|