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
| template<typename T>
class packed_array {
public:
static constexpr inline size_t DEFAULT_SIZE { 0 };
static constexpr inline size_t DEFAULT_CAPACITY { 0xFFFF };
public:
using self_type = packed_array<T>;
using value_type = T;
using pointer = T*;
using const_pointer = T const*;
using reference = T&;
using const_reference = T const&;
using size_type = size_t;
using difference_type = ptrdiff_t;
using iterator = packed_array_iterator<self_type>;
//using const_iterator = packed_array_iterator<self_type, const value_type>;
public:
explicit packed_array(size_type const capacity=DEFAULT_CAPACITY):
array_{ new value_type[capacity] },
capacity_{capacity},
size_{0},
head_{0}, tail_{0}
{}
explicit packed_array(self_type const & other):
array_{ new value_type[other.capacity_] },
capacity_{ other.capacity_ },
size_{ other.size_ },
head_{ other.head_ }, tail_{ other.tail_ }
{
std::copy(other.begin(), other.end(), array_);
}
~packed_array() { delete [] array_; }
iterator begin() { return iterator(this, head_); }
iterator end() { return iterator(this, tail_); }
reference operator[](size_type const id) {
return array_[id];
}
const_reference operator[](size_type const id) const {
return array_[id];
}
reference front() {
return array_[head_];
}
const_reference front() const {
return array_[head_];
}
reference back() {
return array_[tail_-1];
}
const_reference back() const {
return array_[tail_-1];
}
size_type const & size() const {
return size_;
}
void increment_tail() {
++tail_;
++size_;
}
void decrement_tail() {
--tail_;
--size_;
}
void increment_head() {
++head_;
--size_;
}
void decrement_head() {
--head_;
++size_;
}
void push_back(value_type const & item) {
if(size_ == capacity_) {
//drop the current item
} else {
array_[tail_] = item;
increment_tail();
}
}
void push(value_type const & item) {
if(size_ == capacity_) {
//drop the current item
} else if(head_ != 0) {
decrement_head();
array_[head_] = item;
} else {
push_back(item);
}
}
void erase(size_type const id) {
if(id != head_) {
std::swap(array_[head_], array_[id]);
}
increment_head();
}
private:
value_type* array_;
size_type capacity_;
size_type size_;
size_type head_;
size_type tail_;
}; |
Partager