smatskevich

DoubleVector

May 4th, 2021
473
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <exception>
  2. #include <iostream>
  3. #include <stdexcept>
  4.  
  5. class Vector {
  6.  public:
  7.   Vector();
  8.   ~Vector();
  9.  
  10.   double at(unsigned int index) const;
  11.   double operator[](unsigned int index) const { return at(index); }
  12.   unsigned int size() const { return size_; }
  13.   bool empty() const { return size_ == 0u;}
  14.   void push_back(double value);
  15.  
  16.  private:
  17.   static const unsigned int kInitialSize = 2;
  18.  
  19.   double* buffer_;
  20.   unsigned int size_;  // Количество хранимых элементов
  21.   unsigned int capacity_;  // Размер буфера
  22.  
  23.   void increase_buffer();
  24. };
  25.  
  26. Vector::Vector() :
  27.   buffer_(nullptr),
  28.   size_(0),
  29.   capacity_(0) {
  30. }
  31.  
  32. Vector::~Vector() {
  33.   delete[] buffer_;
  34. }
  35.  
  36. double Vector::at(unsigned int index) const {
  37.   if (index >= size_) throw std::out_of_range("No such index");
  38.   return buffer_[index];
  39. }
  40.  
  41. void Vector::push_back(double value) {
  42.   if (size_ == capacity_) {
  43.     increase_buffer();
  44.   }
  45.   buffer_[size_++] = value;
  46. }
  47.  
  48. void Vector::increase_buffer() {
  49.   unsigned int new_capacity = capacity_ == 0 ? kInitialSize : 2 * capacity_;
  50.   double* new_buffer = new double[new_capacity];
  51.   for (unsigned int i = 0; i < size_; ++i) {
  52.     new_buffer[i] = buffer_[i];
  53.   }
  54.   delete[] buffer_;
  55.   buffer_ = new_buffer;
  56.   capacity_ = new_capacity;
  57. }
  58.  
  59. void do_stuff() {
  60.   Vector v;
  61.   v.push_back(4.0);
  62.   v.push_back(5.0);
  63.   v.push_back(3.0);
  64.   v.push_back(2.0);
  65.   v.push_back(1.0);
  66.   for (unsigned int i = 0; i <= v.size(); ++i) {
  67.     std::cout << v[i] << " ";
  68.   }
  69. }
  70.  
  71. int main() {
  72.   try {
  73.     do_stuff();
  74.   } catch (const std::exception& e) {
  75.     std::cout << "ERROR! " << e.what();
  76.   }
  77.   return 0;
  78. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×