Punchcard

Array container

Nov 1st, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | Source Code | 0 0
  1. #pragma once
  2.  
  3. #include <array>
  4. #include <stdexcept>
  5. #include <iterator>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. template <typename T, size_t N>
  11. class StackVector {
  12. public:
  13.     explicit StackVector(size_t a_size = 0) : index_(a_size) {
  14.         if (a_size > arr.size()) {
  15.             throw invalid_argument("Expectations far too large");          
  16.         }
  17.     }
  18.    
  19.     T& operator[](size_t index) {
  20.         if (index >= index_) {
  21.             throw invalid_argument("Out of bounds");
  22.         }
  23.         return arr[index];
  24.     }
  25.     const T& operator[](size_t index) const {
  26.         try {
  27.             return arr[index];         
  28.         } catch (invalid_argument& e) {
  29.             throw(e.what());       
  30.         }      
  31.     }
  32.  
  33.     typename array<T, N>::iterator begin() {
  34.         return arr.begin();
  35.     }
  36.     typename array<T, N>::iterator end() {     
  37.         return arr.begin() + index_;
  38.     }
  39.     typename array<T, N>::iterator begin() const {
  40.         return begin();
  41.     }
  42.     typename array<T, N>::iterator end() const {
  43.         return end();
  44.     }
  45.  
  46.     size_t Size() const {
  47.         return index_;     
  48.     }
  49.     size_t Capacity() const {
  50.         return arr.size();
  51.     }
  52.  
  53.     void PushBack(const T& value) {
  54.         if(index_ >= arr.size()) {
  55.             throw overflow_error("Container full");
  56.         }
  57.         arr[index_++] = value;     
  58.     }
  59.     T PopBack() {
  60.         if(index_ == 0) {
  61.             throw underflow_error("Container empty");
  62.         }      
  63.         return arr[--index_];
  64.     }
  65. private:
  66.     size_t index_ = 0;
  67.     array<T, N> arr;
  68. };
  69.  
Advertisement
Add Comment
Please, Sign In to add comment