1 #ifndef DASYNQ_SVEC_H_INCLUDED
2 #define DASYNQ_SVEC_H_INCLUDED
9 // Vector with possibility to shrink capacity arbitrarily
23 if (size_v == capacity_v) {
24 // double capacity now:
25 if (capacity_v == 0) capacity_v = 1;
26 T * new_array = (T *) std::malloc(capacity_v * 2 * sizeof(T));
27 if (new_array == nullptr) {
28 throw std::bad_alloc();
30 for (size_t i = 0; i < size_v; i++) {
31 new (&new_array[i]) T(std::move(array[i]));
41 using size_type = size_t;
43 svector() : array(nullptr), size_v(0), capacity_v(0)
48 svector(const svector<T> &other)
50 capacity_v = other.size_v;
51 size_v = other.size_v;
52 array = (T *) std::malloc(capacity_v * sizeof(T));
53 if (array == nullptr) {
54 throw std::bad_alloc();
56 for (size_t i = 0; i < size_v; i++) {
57 new (&array[i]) T(other[i]);
63 for (size_t i = 0; i < size_v; i++) {
69 void push_back(const T &t)
72 new (&array[size_v]) T(t);
79 new (&array[size_v]) T(t);
83 template <typename ...U>
84 void emplace_back(U... args)
87 new (&array[size_v]) T(args...);
96 T &operator[](size_t index)
101 const T &operator[](size_t index) const
111 size_t capacity() const
121 void reserve(size_t amount)
123 if (capacity_v < amount) {
124 T * new_array = (T *) std::malloc(amount * sizeof(T));
125 if (new_array == nullptr) {
126 throw std::bad_alloc();
128 for (size_t i = 0; i < size_v; i++) {
129 new (&new_array[i]) T(std::move(array[i]));
138 void shrink_to(size_t amount)
140 if (capacity_v > amount) {
141 T * new_array = (T *) std::malloc(amount * sizeof(T));
142 if (new_array == nullptr) {
145 for (size_t i = 0; i < size_v; i++) {
146 new (&new_array[i]) T(std::move(array[i]));
157 return array[size_v - 1];
165 const T *begin() const
172 return array + size_v;
177 return array + size_v;