Advertisement
Guest User

Untitled

a guest
Sep 24th, 2023
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4.  
  5.  
  6. template<typename T> class Deque {
  7. public:
  8. Deque(): current_capacity(8) {
  9. arr = malloc.allocate(current_capacity);
  10. }
  11.  
  12. size_t size() const {
  13. return current_size;
  14. }
  15.  
  16. void push_back(const T &item);
  17. void push_front(const T &item);
  18. T pop_front();
  19. T pop_back();
  20.  
  21. T front() const {
  22. return *((arr + push_front_position) - 1);
  23. }
  24.  
  25. T back() const {
  26. return *((arr + push_back_position) - 1);
  27. }
  28.  
  29. private:
  30. T *arr = nullptr;
  31. void reallocate();
  32. size_t current_size = 0;
  33. size_t current_capacity;
  34. size_t push_back_position = (current_capacity / 2) + 1;
  35. size_t push_front_position = current_capacity / 2;
  36. static std::allocator<T> malloc;
  37. };
  38.  
  39. template<typename T> std::allocator<T> Deque<T>::malloc;
  40.  
  41.  
  42. template<typename T> void Deque<T>::reallocate() {
  43. T *new_arr = malloc.allocate(current_capacity * 2);
  44.  
  45. std::uninitialized_copy(arr, arr + current_capacity, new_arr);
  46.  
  47. for (size_t i = 0; i != current_capacity; ++i)
  48. malloc.destroy(arr + i);
  49.  
  50. malloc.deallocate(arr, current_capacity);
  51.  
  52. arr = new_arr;
  53. current_capacity = current_capacity * 2;
  54. push_back_position = (current_capacity / 2) + 1;
  55. push_front_position = current_capacity / 2;
  56. }
  57.  
  58.  
  59. template<typename T> void Deque<T>::push_back(const T &item) {
  60. if (current_size + 1 > current_capacity)
  61. reallocate();
  62.  
  63. malloc.construct(arr + push_back_position, item);
  64.  
  65. ++push_back_position;
  66. ++current_size;
  67. }
  68.  
  69.  
  70. template<typename T> void Deque<T>::push_front(const T &item) {
  71. if (current_size + 1 > current_capacity)
  72. reallocate();
  73.  
  74. malloc.construct(arr + push_front_position, item);
  75.  
  76. --push_front_position;
  77. ++current_size;
  78. }
  79.  
  80.  
  81. int main() {
  82. Deque<int> test;
  83.  
  84. for (int i = 0; i <= 5; ++i)
  85. test.push_front(i);
  86.  
  87. for (int i = 5; i <= 10; ++i)
  88. test.push_back(i);
  89.  
  90. std::cout << test.front() << std::endl;
  91. std::cout << test.back() << std::endl;
  92.  
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement