Advertisement
AyratT

Untitled

Feb 1st, 2023
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.61 KB | None | 0 0
  1.  
  2. #pragma once
  3. #include <iostream>
  4. #include <cassert>
  5. #include <initializer_list>
  6. #include <algorithm>
  7. #include "array_ptr.h"
  8. #include <numeric>
  9. #include <iterator>
  10. #include <stdexcept>
  11. #include <cmath>
  12. #include <utility>
  13.  
  14. struct ReserveProxyObj {
  15.     size_t capacity_to_reserve_;
  16.     ReserveProxyObj(size_t capacity_to_reserve)
  17.         : capacity_to_reserve_(capacity_to_reserve) {}
  18. };
  19.  
  20. ReserveProxyObj Reserve(size_t capacity_to_reserve) {
  21.     return ReserveProxyObj(capacity_to_reserve);
  22. }
  23.  
  24. template <typename Type>
  25. class SimpleVector {
  26. public:
  27.     using Iterator = Type*;
  28.     using ConstIterator = const Type*;
  29.  
  30.     SimpleVector() noexcept = default;
  31.  
  32.     SimpleVector(ReserveProxyObj obj) {
  33.         Reserve(obj.capacity_to_reserve_);
  34.     }
  35.  
  36.  
  37.     // Создаёт вектор из size элементов, инициализированных значением по умолчанию
  38.     explicit SimpleVector(size_t size) {
  39.         ArrayPtr<Type> simple_vector_copy(size);
  40.         simple_vector_copy.swap(simple_vector_);
  41.         size_ = size;
  42.         capacity_ = size;
  43.         //std::fill(begin(), end(), Type{});
  44.     }
  45.  
  46.     // Создаёт вектор из size элементов, инициализированных значением value
  47.     SimpleVector(size_t size, const Type& value) {
  48.         ArrayPtr<Type> simple_vector_copy(size);
  49.         std::fill(simple_vector_copy.Get(), simple_vector_copy.Get() + size, value);
  50.         simple_vector_.swap(simple_vector_copy);
  51.         size_ = size;
  52.         capacity_ = size;
  53.     }
  54.  
  55.     // Создаёт вектор из std::initializer_list
  56.     SimpleVector(std::initializer_list<Type> init) {
  57.         ArrayPtr<Type> simple_vector_copy(init.size());
  58.         std::copy(std::make_move_iterator(init.begin()), std::make_move_iterator(init.end()),
  59.             simple_vector_copy.Get());
  60.         simple_vector_.swap(simple_vector_copy);
  61.         size_ = init.size();
  62.         capacity_ = init.size();
  63.     }
  64.  
  65.     // Конструктор копирования
  66.     SimpleVector(const SimpleVector& other) {
  67.         SimpleVector<Type> simple_vector_copy(other.size_);
  68.         std::copy(other.begin(), other.end(),
  69.             simple_vector_copy.begin());
  70.         simple_vector_copy.size_ = other.size_;
  71.         simple_vector_copy.capacity_ = other.capacity_;
  72.         swap(simple_vector_copy);
  73.     }
  74.  
  75.     // конструктор перемещения
  76.     SimpleVector(SimpleVector&& other) {
  77.         simple_vector_ = std::move(other.simple_vector_);
  78.         size_ = std::move(other.size_);
  79.         capacity_ = std::move(other.capacity_);
  80.         other.size_ = 0;
  81.         other.capacity_ = 0;
  82.     }
  83.  
  84.     // Оператор присваивания
  85.     SimpleVector& operator=(const SimpleVector& rhs) {
  86.         if (simple_vector_.Get() != rhs.simple_vector_.Get()) {
  87.             ArrayPtr<Type> simple_vector_copy(rhs.size_);
  88.             std::copy(std::make_move_iterator(rhs.simple_vector_.Get()), std::make_move_iterator(rhs.simple_vector_.Get() + rhs.size_),
  89.                 simple_vector_copy.Get());
  90.             simple_vector_.swap(simple_vector_copy);
  91.             size_ = std::move(rhs.size_);
  92.             capacity_ = std::move(rhs.capacity_);
  93.         }
  94.         return *this;
  95.     }
  96.  
  97.     // Добавляет элемент в конец вектора
  98.     // При нехватке места увеличивает вдвое вместимость вектора
  99.     void PushBack(Type item) {
  100.         if (size_ < capacity_) {
  101.             simple_vector_[size_] = std::move(item);
  102.             ++size_;
  103.         }
  104.         else {
  105.             SimpleVector<Type> simple_vector_copy(std::max(size_ * 2, size_t(1)));
  106.             std::copy(std::make_move_iterator(begin()), std::make_move_iterator(end()),
  107.                 simple_vector_copy.begin());
  108.             simple_vector_copy[size_] = std::move(item);
  109.             simple_vector_copy.size_ = size_ + 1;
  110.             swap(simple_vector_copy);
  111.         }
  112.     }
  113.  
  114.     // Вставляет значение value в позицию pos.
  115.     // Возвращает итератор на вставленное значение
  116.     // Если перед вставкой значения вектор был заполнен полностью,
  117.     // вместимость вектора должна увеличиться вдвое, а для вектора вместимостью 0 стать равной 1
  118.  
  119. Iterator Insert(ConstIterator pos, Type value) {
  120.         size_t index = size_t(pos - begin());
  121.         if (size_ < capacity_) {
  122.             std::copy_backward(std::make_move_iterator(begin() + index), std::make_move_iterator(end()), end() + 1);
  123.             simple_vector_[index] = std::move(value);
  124.             ++size_;
  125.         }
  126.         else {
  127.             SimpleVector<Type> simple_vector_copy(std::max(size_ * 2, size_t(1)));
  128.             std::copy(std::make_move_iterator(begin()), std::make_move_iterator(begin() + index), simple_vector_copy.begin());
  129.             simple_vector_copy[index] = std::move(value);
  130.             std::copy(std::make_move_iterator(begin() + index), std::make_move_iterator(end()), simple_vector_copy.begin() + index + 1);
  131.             simple_vector_copy.size_ = size_ + 1;
  132.             swap(simple_vector_copy);
  133.         }
  134.         return begin() + index;
  135.     }
  136.  
  137.     // "Удаляет" последний элемент вектора. Вектор не должен быть пустым
  138.     void PopBack() noexcept {
  139.         if (size_ > 0) {
  140.             --size_;
  141.         }
  142.     }
  143.  
  144.     // Удаляет элемент вектора в указанной позиции
  145.     Iterator Erase(ConstIterator pos) {
  146.         size_t index = size_t(pos - begin());
  147.         std::copy(std::make_move_iterator(begin() + index + 1), std::make_move_iterator(end()), begin() + index);
  148.         --size_;
  149.         return begin() + index;
  150.     }
  151.  
  152.     // Обменивает значение с другим вектором
  153.     void swap(SimpleVector& other) noexcept {
  154.         simple_vector_.swap(other.simple_vector_);
  155.         std::swap(size_, other.size_);
  156.         std::swap(capacity_, other.capacity_);
  157.     }
  158.  
  159.     // Возвращает количество элементов в массиве
  160.     size_t GetSize() const noexcept {
  161.         return size_;
  162.     }
  163.  
  164.     // Возвращает вместимость массива
  165.     size_t GetCapacity() const noexcept {
  166.         return capacity_;
  167.     }
  168.  
  169.     // Сообщает, пустой ли массив
  170.     bool IsEmpty() const noexcept {
  171.         return size_ == 0;
  172.     }
  173.  
  174.     // Возвращает ссылку на элемент с индексом index
  175.     Type& operator[](size_t index) noexcept {
  176.         assert(index < size_);
  177.         return simple_vector_[index];
  178.     }
  179.  
  180.     // Возвращает константную ссылку на элемент с индексом index
  181.     const Type& operator[](size_t index) const noexcept {
  182.         assert(index < size_);
  183.         return simple_vector_[index];
  184.     }
  185.  
  186.     // Возвращает константную ссылку на элемент с индексом index
  187.     // Выбрасывает исключение std::out_of_range, если index >= size
  188.     Type& At(size_t index) {
  189.         if (index >= size_) {
  190.             throw std::out_of_range("out_of_range");
  191.         }
  192.         else {
  193.             return simple_vector_[index];
  194.         }
  195.     }
  196.  
  197.     // Возвращает константную ссылку на элемент с индексом index
  198.     // Выбрасывает исключение std::out_of_range, если index >= size
  199.     const Type& At(size_t index) const {
  200.         if (index >= size_) {
  201.             throw std::out_of_range("out_of_range");
  202.         }
  203.         else {
  204.             return simple_vector_[index];
  205.         }
  206.     }
  207.  
  208.     // Обнуляет размер массива, не изменяя его вместимость
  209.     void Clear() noexcept {
  210.         size_ = 0;
  211.     }
  212.  
  213.     void Reserve(size_t new_capacity) {
  214.         if (new_capacity > capacity_) {
  215.             SimpleVector<Type> simple_vector_copy(new_capacity);
  216.             std::copy(begin(), end(), simple_vector_copy.begin());
  217.             simple_vector_copy.size_ = size_;
  218.             swap(simple_vector_copy);
  219.         }
  220.     }
  221.  
  222.     // Изменяет размер массива.
  223.     // При увеличении размера новые элементы получают значение по умолчанию для типа Type
  224.     void Resize(size_t new_size) {
  225.         if (new_size <= size_) {
  226.             size_ = new_size;
  227.         }
  228.         else if (new_size <= capacity_) {
  229.             //std::generate(std::make_move_iterator(simple_vector_.Get()), std::make_move_iterator(simple_vector_.Get() + new_size), []() {return Type{};});
  230.             auto first = simple_vector_.Get();
  231.             auto last = simple_vector_.Get() + new_size;
  232.  
  233.            for (; first != last;
  234.  
  235. ++first)
  236.                 *first = (Type{});
  237.             /*for (size_t i = 0; i < new_size; ++i) {
  238.                 simple_vector_[i] = (Type{})
  239.             }*/
  240.             size_ = new_size;
  241.         }
  242.         else {
  243.             SimpleVector<Type> simple_vector_copy_(std::max(capacity_ * 2, new_size));
  244.             std::copy(std::make_move_iterator(begin()), std::make_move_iterator(end()), simple_vector_copy_.begin());
  245.             swap(simple_vector_copy_);
  246.         }
  247.     }
  248.  
  249.     // Возвращает итератор на начало массива
  250.     // Для пустого массива может быть равен (или не равен) nullptr
  251.     Iterator begin() noexcept {
  252.         return simple_vector_.Get();
  253.     }
  254.  
  255.     // Возвращает итератор на элемент, следующий за последним
  256.     // Для пустого массива может быть равен (или не равен) nullptr
  257.     Iterator end() noexcept {
  258.         return simple_vector_.Get() + size_;
  259.     }
  260.  
  261.     // Возвращает константный итератор на начало массива
  262.     // Для пустого массива может быть равен (или не равен) nullptr
  263.     ConstIterator begin() const noexcept {
  264.         return simple_vector_.Get();
  265.     }
  266.  
  267.     // Возвращает итератор на элемент, следующий за последним
  268.     // Для пустого массива может быть равен (или не равен) nullptr
  269.     ConstIterator end() const noexcept {
  270.         return simple_vector_.Get() + size_;
  271.     }
  272.  
  273.     // Возвращает константный итератор на начало массива
  274.     // Для пустого массива может быть равен (или не равен) nullptr
  275.     ConstIterator cbegin() const noexcept {
  276.         return simple_vector_.Get();
  277.     }
  278.  
  279.     // Возвращает итератор на элемент, следующий за последним
  280.     // Для пустого массива может быть равен (или не равен) nullptr
  281.     ConstIterator cend() const noexcept {
  282.         return simple_vector_.Get() + size_;
  283.     }
  284.  
  285. private:
  286.     ArrayPtr<Type> simple_vector_;
  287.     size_t size_ = 0;
  288.     size_t capacity_ = 0;
  289.  
  290. };
  291.  
  292. template <typename Type>
  293. inline bool operator==(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  294.     return std::equal(lhs.begin(), lhs.end(), rhs.begin());
  295. }
  296.  
  297. template <typename Type>
  298. inline bool operator!=(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  299.  
  300.     return !(lhs == rhs);
  301. }
  302.  
  303. template <typename Type>
  304. inline bool operator<(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  305.     return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
  306. }
  307.  
  308. template <typename Type>
  309. inline bool operator<=(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  310.     return !(rhs < lhs);
  311. }
  312.  
  313. template <typename Type>
  314. inline bool operator>(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  315.     return rhs < lhs;
  316. }
  317.  
  318. template <typename Type>
  319. inline bool operator>=(const SimpleVector<Type>& lhs, const SimpleVector<Type>& rhs) {
  320.     return !(lhs < rhs);
  321. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement