Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstddef>
- #include <initializer_list>
- #include <utility>
- #include <cstring>
- template<typename T>
- class Vector {
- private:
- T* data = nullptr;
- size_t length = 0;
- size_t real_length = 0;
- public:
- Vector() {}
- Vector(const Vector& other) {
- reserve(other.real_length);
- length = other.length;
- for (size_t i = 0; i < length; i++)
- data[i] = other.data[i];
- }
- Vector(std::initializer_list<T> list) {
- for (auto x : list)
- push_back(x);
- }
- ~Vector() {
- for (size_t i = 0; i < length; i++)
- data[i].~T();
- if (data != nullptr) delete[] reinterpret_cast<char*>(data);
- }
- Vector& operator= (const Vector& other) {
- clear();
- reserve(other.length);
- length = other.length;
- for (size_t i = 0; i < length * sizeof(T); i++)
- new (data + i) T(other.data[i]);
- return *this;
- }
- void reserve(size_t n, bool call_desctructors = true) {
- if (n <= real_length) return;
- T* new_data = reinterpret_cast<T*>(new char[n * sizeof(T)]);
- try {
- for (size_t i = 0; i < length; i++)
- new (new_data + i) T(data[i]);
- } catch (...) {
- delete[] reinterpret_cast<char*>(data);
- throw;
- }
- real_length = n;
- if (call_desctructors) {
- for (size_t i = 0; i < length; i++)
- data[i].~T();
- }
- if (data != nullptr) delete[] reinterpret_cast<char*>(data);
- data = new_data;
- }
- void resize(size_t n) {
- bool need_to_call_destructors = false;
- if (n > real_length) {
- reserve(n, false);
- need_to_call_destructors = true;
- }
- if (n > length) {
- for (size_t i = length; i < n; i++)
- new (data + i) T();
- if (need_to_call_destructors) {
- for (size_t i = 0; i < length; i++)
- data[i].~T();
- }
- } else if (n < length) {
- for (size_t i = n; i < length; i++)
- data[i].~T();
- }
- length = n;
- }
- size_t size() const {
- return length;
- }
- size_t capacity() const {
- return real_length;
- }
- T* begin() {
- return data;
- }
- T* end() {
- return data + length;
- }
- void push_back(const T& x) {
- if (length == 0) {
- reserve(1);
- } else if (length == real_length) {
- reserve(real_length * 2);
- }
- ++length;
- try {
- new (data + (length - 1)) T(x);
- } catch (...) {
- --length;
- }
- }
- void push_back(T&& x) {
- if (length == 0) {
- reserve(1);
- } else if (length == real_length) {
- reserve(real_length * 2);
- }
- ++length;
- try {
- new (data + (length - 1)) T(std::move(x));
- } catch (...) {
- --length;
- }
- }
- void pop_back() {
- data[length-1].~T();
- --length;
- }
- void clear() {
- for (size_t i = 0; i < length; i++)
- data[i].~T();
- length = 0;
- }
- void swap(Vector& other) {
- std::swap(length, other.length);
- std::swap(real_length, other.real_length);
- std::swap(data, other.data);
- }
- T& operator[] (size_t i) {
- return data[i];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement