Last active
October 13, 2017 23:27
-
-
Save zhrkvl/3957b71ca15c7f8294a99e436bb8c740 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
class Vector { | |
private: | |
T *array; | |
size_t cap; | |
size_t end; // last element pointer | |
public: | |
Vector() : Vector(1) {} | |
explicit Vector(size_t initialCap) { | |
cap = initialCap; | |
end = initialCap; // first unused | |
array = new T[cap]; | |
} | |
Vector(size_t initialCap, T fillValue) { | |
cap = initialCap; | |
end = initialCap; // first unused | |
array = new T[cap]; | |
fill(array, array + end, fillValue); | |
} | |
void reserve(size_t new_cap) { | |
if (new_cap < cap) { return; } | |
size_t newSize = new_cap; | |
T *future = new T[newSize]; | |
copy(array, array + end, future); | |
delete[] array; | |
array = future; | |
cap = newSize; | |
} | |
void resize(size_t capacity) { | |
if (capacity > cap) { | |
reserve(capacity); | |
end = capacity; | |
return; | |
} | |
end = capacity; | |
} | |
T &operator[](const size_t index) { | |
return array[index]; | |
} | |
void add(const T x) { | |
if (end >= cap) { | |
size_t newSize = (ceill((cap > 0 ? cap : 1) * 1.5L)); | |
T *future = new T[newSize]; | |
copy(array, array + end, future); | |
delete[] array; | |
array = future; | |
cap = newSize; | |
} | |
array[end++] = x; | |
} | |
void addl(const T &x) { | |
if (end >= cap) { | |
size_t newSize = (ceill((cap > 0 ? cap : 1) * 1.5L)); | |
T *future = new T[newSize]; | |
copy(array, array + end, future); | |
delete[] array; | |
array = future; | |
cap = newSize; | |
} | |
array[end++] = x; | |
} | |
void del_back() { | |
if (end == 0) return; | |
end--; | |
} | |
T &back() { | |
return array[end - 1]; | |
} | |
size_t size() const { | |
return end; | |
} | |
size_t capacity() const { | |
return cap; | |
} | |
Vector<T> & | |
operator=(const Vector<T> &x) { | |
reserve(x.end); | |
copy(x.array, x.array + x.end, this->array); | |
this->cap = x.cap; | |
this->end = x.end; | |
return *this; | |
} | |
~Vector() { | |
delete[] array; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment